From 3b2dbd3650ea812f00b4d1a9e4e18a5bc7420ab5 Mon Sep 17 00:00:00 2001 From: KxmischesDomi Date: Thu, 10 Feb 2022 18:22:00 +0100 Subject: [PATCH 01/92] 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 02/92] 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 03/92] 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 04/92] 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 05/92] 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 06/92] 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 07/92] 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 08/92] 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 09/92] 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 10/92] 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 11/92] 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 12/92] 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 13/92] 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 14/92] 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 15/92] 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 16/92] 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 17/92] 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 18/92] 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 19/92] 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 20/92] 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 21/92] 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 22/92] 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 23/92] 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 24/92] 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 25/92] 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 26/92] 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 27/92] 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 28/92] 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 29/92] 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 30/92] 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 31/92] 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 32/92] 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 33/92] 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 34/92] 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 35/92] 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 36/92] 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 37/92] 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 38/92] 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 39/92] 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 40/92] 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 41/92] 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 42/92] 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 43/92] 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 44/92] 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 45/92] 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 46/92] 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 47/92] =?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 48/92] 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 49/92] 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 50/92] 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 51/92] 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 52/92] 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 53/92] 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 54/92] 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 55/92] 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 56/92] 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 57/92] 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 58/92] 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 59/92] 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 60/92] 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 61/92] =?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 62/92] =?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 63/92] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-fi?= =?UTF-8?q?xes=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 64/92] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-fi?= =?UTF-8?q?xes=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 65/92] 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 66/92] 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 67/92] 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 68/92] 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 69/92] 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 70/92] 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 71/92] 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 72/92] 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 73/92] 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 74/92] 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 75/92] 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 76/92] 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 77/92] 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 78/92] 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 79/92] 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 80/92] 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 81/92] 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 82/92] 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 83/92] 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 84/92] 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 85/92] 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 86/92] 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 87/92] 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 88/92] 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 89/92] 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 90/92] 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 91/92] 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 92/92] 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