From 96d94fa16e86310655a6e3bec3085a1574429fbc Mon Sep 17 00:00:00 2001 From: tastybento Date: Fri, 25 Oct 2019 16:30:14 -0700 Subject: [PATCH] Fix code smells from sonarcloud analysis --- .../bentobox/challenges/ChallengesAddon.java | 4 +- .../challenges/ChallengesImportManager.java | 711 +++++----- .../challenges/ChallengesManager.java | 14 - .../commands/ChallengesCommand.java | 5 +- .../challenges/panel/admin/EditLoreGUI.java | 1205 +++++++++-------- .../challenges/tasks/TryToComplete.java | 2 +- .../bentobox/challenges/web/WebManager.java | 1 - .../challenges/ChallengesAddonTest.java | 114 -- 8 files changed, 968 insertions(+), 1088 deletions(-) delete mode 100644 src/test/java/world/bentobox/challenges/ChallengesAddonTest.java diff --git a/src/main/java/world/bentobox/challenges/ChallengesAddon.java b/src/main/java/world/bentobox/challenges/ChallengesAddon.java index 8a5ef3a..7e4b3e9 100644 --- a/src/main/java/world/bentobox/challenges/ChallengesAddon.java +++ b/src/main/java/world/bentobox/challenges/ChallengesAddon.java @@ -88,7 +88,7 @@ public class ChallengesAddon extends Addon { * This flag allows to complete challenges in any part of the world. It will not limit * player to their island. Useful for skygrid without protection flags. */ - public static Flag CHALLENGES_WORLD_PROTECTION = + public static final Flag CHALLENGES_WORLD_PROTECTION = new Flag.Builder("CHALLENGES_WORLD_PROTECTION", Material.GRASS_BLOCK).type(Flag.Type.WORLD_SETTING).defaultSetting(true).build(); /** @@ -96,7 +96,7 @@ public class ChallengesAddon extends Addon { * that only Island owner can complete challenge. * By default it is set to Visitor. */ - public static Flag CHALLENGES_ISLAND_PROTECTION = + public static final Flag CHALLENGES_ISLAND_PROTECTION = new Flag.Builder("CHALLENGES_ISLAND_PROTECTION", Material.COMMAND_BLOCK).defaultRank(RanksManager.VISITOR_RANK).build(); diff --git a/src/main/java/world/bentobox/challenges/ChallengesImportManager.java b/src/main/java/world/bentobox/challenges/ChallengesImportManager.java index dfec22d..e0feb65 100644 --- a/src/main/java/world/bentobox/challenges/ChallengesImportManager.java +++ b/src/main/java/world/bentobox/challenges/ChallengesImportManager.java @@ -43,14 +43,14 @@ public class ChallengesImportManager * @param challengesAddon */ public ChallengesImportManager(ChallengesAddon challengesAddon) - { + { this.addon = challengesAddon; } -// --------------------------------------------------------------------- -// Section: Default Challenge Loader -// --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Default Challenge Loader + // --------------------------------------------------------------------- /** @@ -79,45 +79,46 @@ public class ChallengesImportManager } // default configuration should be removed. - // user made configuration should not!. + // user made configuration should not!. boolean removeAtEnd = - !Files.exists(Paths.get(this.addon.getDataFolder().getPath() + "/default.json")); + !Files.exists(Paths.get(this.addon.getDataFolder().getPath() + "/default.json")); // Safe json configuration to Challenges folder. - this.addon.saveResource("default.json", false); + this.addon.saveResource("default.json", false); try { - // This prefix will be used to all challenges. That is a unique way how to separate challenged for - // each game mode. - String uniqueIDPrefix = Utils.getGameMode(world) + "_"; - DefaultDataHolder defaultChallenges = new DefaultJSONHandler(this.addon).loadObject(); + // This prefix will be used to all challenges. That is a unique way how to separate challenged for + // each game mode. + String uniqueIDPrefix = Utils.getGameMode(world) + "_"; + DefaultDataHolder defaultChallenges = new DefaultJSONHandler(this.addon).loadObject(); + if (defaultChallenges != null) { + // All new challenges should get correct ID. So we need to map it to loaded challenges. + defaultChallenges.getChallengeList().forEach(challenge -> { + // Set correct challenge ID + challenge.setUniqueId(uniqueIDPrefix + challenge.getUniqueId()); + // Set up correct level ID if it is necessary + if (!challenge.getLevel().isEmpty()) + { + challenge.setLevel(uniqueIDPrefix + challenge.getLevel()); + } + // Load challenge in memory + manager.loadChallenge(challenge, false, user, user == null); + }); - // All new challenges should get correct ID. So we need to map it to loaded challenges. - defaultChallenges.getChallengeList().forEach(challenge -> { - // Set correct challenge ID - challenge.setUniqueId(uniqueIDPrefix + challenge.getUniqueId()); - // Set up correct level ID if it is necessary - if (!challenge.getLevel().isEmpty()) - { - challenge.setLevel(uniqueIDPrefix + challenge.getLevel()); - } - // Load challenge in memory - manager.loadChallenge(challenge, false, user, user == null); - }); - - defaultChallenges.getLevelList().forEach(challengeLevel -> { - // Set correct level ID - challengeLevel.setUniqueId(uniqueIDPrefix + challengeLevel.getUniqueId()); - // Set correct world name - challengeLevel.setWorld(Util.getWorld(world).getName()); - // Reset names for all challenges. - challengeLevel.setChallenges(challengeLevel.getChallenges().stream(). - map(challenge -> uniqueIDPrefix + challenge). - collect(Collectors.toSet())); - // Load level in memory - manager.loadLevel(challengeLevel, false, user, user == null); - }); + defaultChallenges.getLevelList().forEach(challengeLevel -> { + // Set correct level ID + challengeLevel.setUniqueId(uniqueIDPrefix + challengeLevel.getUniqueId()); + // Set correct world name + challengeLevel.setWorld(Util.getWorld(world).getName()); + // Reset names for all challenges. + challengeLevel.setChallenges(challengeLevel.getChallenges().stream(). + map(challenge -> uniqueIDPrefix + challenge). + collect(Collectors.toSet())); + // Load level in memory + manager.loadLevel(challengeLevel, false, user, user == null); + }); + } } catch (Exception e) { @@ -128,132 +129,132 @@ public class ChallengesImportManager this.addon.getChallengesManager().save(); if (removeAtEnd) - { - // Remove default.yml file from resources to avoid interacting with it. - new File(this.addon.getDataFolder(), "default.json").delete(); - } + { + // Remove default.yml file from resources to avoid interacting with it. + return new File(this.addon.getDataFolder(), "default.json").delete(); + } return true; } - /** - * This method loads downloaded challenges into memory. - * @param user User who calls downloaded challenge loading - * @param world Target world. - * @param downloadString String that need to be loaded via DefaultDataHolder. - * @return true if everything was successful, otherwise false. - */ - public boolean loadDownloadedChallenges(User user, World world, String downloadString) - { - ChallengesManager manager = this.addon.getChallengesManager(); + /** + * This method loads downloaded challenges into memory. + * @param user User who calls downloaded challenge loading + * @param world Target world. + * @param downloadString String that need to be loaded via DefaultDataHolder. + * @return true if everything was successful, otherwise false. + */ + public boolean loadDownloadedChallenges(User user, World world, String downloadString) + { + ChallengesManager manager = this.addon.getChallengesManager(); - // If exist any challenge or level that is bound to current world, then do not load default challenges. - if (manager.hasAnyChallengeData(world.getName())) - { - if (user.isPlayer()) - { - user.sendMessage("challenges.errors.exist-challenges-or-levels"); - } - else - { - this.addon.logWarning("challenges.errors.exist-challenges-or-levels"); - } + // If exist any challenge or level that is bound to current world, then do not load default challenges. + if (manager.hasAnyChallengeData(world.getName())) + { + if (user.isPlayer()) + { + user.sendMessage("challenges.errors.exist-challenges-or-levels"); + } + else + { + this.addon.logWarning("challenges.errors.exist-challenges-or-levels"); + } - return false; - } + return false; + } - try - { - // This prefix will be used to all challenges. That is a unique way how to separate challenged for - // each game mode. - String uniqueIDPrefix = Utils.getGameMode(world) + "_"; - DefaultDataHolder downloadedChallenges = new DefaultJSONHandler(this.addon).loadWebObject(downloadString); + try + { + // This prefix will be used to all challenges. That is a unique way how to separate challenged for + // each game mode. + String uniqueIDPrefix = Utils.getGameMode(world) + "_"; + DefaultDataHolder downloadedChallenges = new DefaultJSONHandler(this.addon).loadWebObject(downloadString); - // All new challenges should get correct ID. So we need to map it to loaded challenges. - downloadedChallenges.getChallengeList().forEach(challenge -> { - // Set correct challenge ID - challenge.setUniqueId(uniqueIDPrefix + challenge.getUniqueId()); - // Set up correct level ID if it is necessary - if (!challenge.getLevel().isEmpty()) - { - challenge.setLevel(uniqueIDPrefix + challenge.getLevel()); - } - // Load challenge in memory - manager.loadChallenge(challenge, false, user, user == null); - }); + // All new challenges should get correct ID. So we need to map it to loaded challenges. + downloadedChallenges.getChallengeList().forEach(challenge -> { + // Set correct challenge ID + challenge.setUniqueId(uniqueIDPrefix + challenge.getUniqueId()); + // Set up correct level ID if it is necessary + if (!challenge.getLevel().isEmpty()) + { + challenge.setLevel(uniqueIDPrefix + challenge.getLevel()); + } + // Load challenge in memory + manager.loadChallenge(challenge, false, user, user == null); + }); - downloadedChallenges.getLevelList().forEach(challengeLevel -> { - // Set correct level ID - challengeLevel.setUniqueId(uniqueIDPrefix + challengeLevel.getUniqueId()); - // Set correct world name - challengeLevel.setWorld(Util.getWorld(world).getName()); - // Reset names for all challenges. - challengeLevel.setChallenges(challengeLevel.getChallenges().stream(). - map(challenge -> uniqueIDPrefix + challenge). - collect(Collectors.toSet())); - // Load level in memory - manager.loadLevel(challengeLevel, false, user, user == null); - }); - } - catch (Exception e) - { - e.printStackTrace(); - return false; - } + downloadedChallenges.getLevelList().forEach(challengeLevel -> { + // Set correct level ID + challengeLevel.setUniqueId(uniqueIDPrefix + challengeLevel.getUniqueId()); + // Set correct world name + challengeLevel.setWorld(Util.getWorld(world).getName()); + // Reset names for all challenges. + challengeLevel.setChallenges(challengeLevel.getChallenges().stream(). + map(challenge -> uniqueIDPrefix + challenge). + collect(Collectors.toSet())); + // Load level in memory + manager.loadLevel(challengeLevel, false, user, user == null); + }); + } + catch (Exception e) + { + addon.getPlugin().logStacktrace(e); + return false; + } - this.addon.getChallengesManager().save(); + this.addon.getChallengesManager().save(); - return true; - } + return true; + } -// --------------------------------------------------------------------- -// Section: Default generation -// --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Default generation + // --------------------------------------------------------------------- /** * Create method that can generate default challenge file from existing challenges in given world. * This method will create default.json file in Challenges folder. - * @param user User who calls this method. + * @param user User who calls this method. * @param world from which challenges must be stored. - * @param overwrite indicates if existing default.json file can be overwritten. - * @return true if everything was successful, otherwise false + * @param overwrite indicates if existing default.json file can be overwritten. + * @return true if everything was successful, otherwise false */ public boolean generateDefaultChallengeFile(User user, World world, boolean overwrite) { File defaultFile = new File(this.addon.getDataFolder(), "default.json"); if (defaultFile.exists()) - { - if (overwrite) - { - if (user.isPlayer()) - { - user.sendMessage("challenges.messages.defaults-file-overwrite"); - } - else - { - this.addon.logWarning("challenges.messages.defaults-file-overwrite"); - } + { + if (overwrite) + { + if (user.isPlayer()) + { + user.sendMessage("challenges.messages.defaults-file-overwrite"); + } + else + { + this.addon.logWarning("challenges.messages.defaults-file-overwrite"); + } - defaultFile.delete(); - } - else - { - if (user.isPlayer()) - { - user.sendMessage("challenges.errors.defaults-file-exist"); - } - else - { - this.addon.logWarning("challenges.errors.defaults-file-exist"); - } + defaultFile.delete(); + } + else + { + if (user.isPlayer()) + { + user.sendMessage("challenges.errors.defaults-file-exist"); + } + else + { + this.addon.logWarning("challenges.errors.defaults-file-exist"); + } - return false; - } - } + return false; + } + } try { @@ -262,102 +263,102 @@ public class ChallengesImportManager String replacementString = Utils.getGameMode(world) + "_"; ChallengesManager manager = this.addon.getChallengesManager(); - List challengeList = manager.getAllChallenges(world). - stream(). - map(challenge -> { - // Use clone to avoid any changes in existing challenges. - Challenge clone = challenge.clone(); - // Remove world name from challenge id. - clone.setUniqueId(challenge.getUniqueId().replaceFirst(replacementString, "")); - // Remove world name from level id. - clone.setLevel(challenge.getLevel().replaceFirst(replacementString, "")); + List challengeList = manager.getAllChallenges(world). + stream(). + map(challenge -> { + // Use clone to avoid any changes in existing challenges. + Challenge clone = challenge.clone(); + // Remove world name from challenge id. + clone.setUniqueId(challenge.getUniqueId().replaceFirst(replacementString, "")); + // Remove world name from level id. + clone.setLevel(challenge.getLevel().replaceFirst(replacementString, "")); - return clone; - }). - collect(Collectors.toList()); + return clone; + }). + collect(Collectors.toList()); - List levelList = manager.getLevels(world). - stream(). - map(challengeLevel -> { - // Use clone to avoid any changes in existing levels. - ChallengeLevel clone = challengeLevel.clone(); - // Remove world name from level ID. - clone.setUniqueId(challengeLevel.getUniqueId().replaceFirst(replacementString, "")); - // Remove world name. - clone.setWorld(""); - // Challenges must be reassign, as they also contains world name. - clone.setChallenges(challengeLevel.getChallenges().stream(). - map(challenge -> challenge.replaceFirst(replacementString, "")). - collect(Collectors.toSet())); + List levelList = manager.getLevels(world). + stream(). + map(challengeLevel -> { + // Use clone to avoid any changes in existing levels. + ChallengeLevel clone = challengeLevel.clone(); + // Remove world name from level ID. + clone.setUniqueId(challengeLevel.getUniqueId().replaceFirst(replacementString, "")); + // Remove world name. + clone.setWorld(""); + // Challenges must be reassign, as they also contains world name. + clone.setChallenges(challengeLevel.getChallenges().stream(). + map(challenge -> challenge.replaceFirst(replacementString, "")). + collect(Collectors.toSet())); - return clone; - }). - collect(Collectors.toList()); + return clone; + }). + collect(Collectors.toList()); - DefaultDataHolder defaultChallenges = new DefaultDataHolder(); - defaultChallenges.setChallengeList(challengeList); - defaultChallenges.setLevelList(levelList); - defaultChallenges.setVersion(this.addon.getDescription().getVersion()); + DefaultDataHolder defaultChallenges = new DefaultDataHolder(); + defaultChallenges.setChallengeList(challengeList); + defaultChallenges.setLevelList(levelList); + defaultChallenges.setVersion(this.addon.getDescription().getVersion()); - BufferedWriter writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(defaultFile), StandardCharsets.UTF_8)); - writer.write(Objects.requireNonNull( - new DefaultJSONHandler(this.addon).toJsonString(defaultChallenges))); - writer.close(); + try (BufferedWriter writer = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(defaultFile), StandardCharsets.UTF_8))) { + writer.write(Objects.requireNonNull( + new DefaultJSONHandler(this.addon).toJsonString(defaultChallenges))); + } } } catch (IOException e) { - if (user.isPlayer()) - { - user.sendMessage("challenges.errors.defaults-file-error"); - } + if (user.isPlayer()) + { + user.sendMessage("challenges.errors.defaults-file-error"); + } - this.addon.logError("Could not save json file: " + e.getMessage()); - return false; - } + this.addon.logError("Could not save json file: " + e.getMessage()); + return false; + } finally - { - if (user.isPlayer()) - { - user.sendMessage("challenges.messages.defaults-file-completed", "[world]", world.getName()); - } - else - { - this.addon.logWarning("challenges.messages.defaults-file-completed"); - } - } + { + if (user.isPlayer()) + { + user.sendMessage("challenges.messages.defaults-file-completed", "[world]", world.getName()); + } + else + { + this.addon.logWarning("challenges.messages.defaults-file-completed"); + } + } - return true; - } + return true; + } -// --------------------------------------------------------------------- -// Section: Private classes for default challenges -// --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Private classes for default challenges + // --------------------------------------------------------------------- /** * This Class allows to load default challenges and their levels as objects much easier. */ - private static final class DefaultJSONHandler + private static final class DefaultJSONHandler { - /** - * This constructor inits JSON builder that will be used to parse challenges. - * @param addon Challenges Adddon - */ - DefaultJSONHandler(ChallengesAddon addon) + /** + * This constructor inits JSON builder that will be used to parse challenges. + * @param addon Challenges Adddon + */ + DefaultJSONHandler(ChallengesAddon addon) { - GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization(); - // Register adapters - builder.registerTypeAdapterFactory(new BentoboxTypeAdapterFactory(addon.getPlugin())); - // Keep null in the database - builder.serializeNulls(); - // Allow characters like < or > without escaping them - builder.disableHtmlEscaping(); + GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization(); + // Register adapters + builder.registerTypeAdapterFactory(new BentoboxTypeAdapterFactory(addon.getPlugin())); + // Keep null in the database + builder.serializeNulls(); + // Allow characters like < or > without escaping them + builder.disableHtmlEscaping(); - this.addon = addon; - this.gson = builder.setPrettyPrinting().create(); + this.addon = addon; + this.gson = builder.setPrettyPrinting().create(); } @@ -366,7 +367,7 @@ public class ChallengesImportManager * @param instance Instance that must be parsed to json string. * @return String that contains JSON information from instance object. */ - String toJsonString(DefaultDataHolder instance) + String toJsonString(DefaultDataHolder instance) { // Null check if (instance == null) @@ -375,193 +376,193 @@ public class ChallengesImportManager return null; } - return this.gson.toJson(instance); + return this.gson.toJson(instance); } - /** - * This method creates and adds to list all objects from default.json file. - * @return List of all objects from default.json that is with T instance. - */ - DefaultDataHolder loadObject() - { - File defaultFile = new File(this.addon.getDataFolder(), "default.json"); + /** + * This method creates and adds to list all objects from default.json file. + * @return List of all objects from default.json that is with T instance. + */ + DefaultDataHolder loadObject() + { + File defaultFile = new File(this.addon.getDataFolder(), "default.json"); - try (InputStreamReader reader = new InputStreamReader(new FileInputStream(defaultFile), StandardCharsets.UTF_8)) - { - DefaultDataHolder object = this.gson.fromJson(reader, DefaultDataHolder.class); + try (InputStreamReader reader = new InputStreamReader(new FileInputStream(defaultFile), StandardCharsets.UTF_8)) + { + DefaultDataHolder object = this.gson.fromJson(reader, DefaultDataHolder.class); - reader.close(); // NOSONAR Required to keep OS file handlers low and not rely on GC + reader.close(); // NOSONAR Required to keep OS file handlers low and not rely on GC - return object; - } - catch (FileNotFoundException e) - { - this.addon.logError("Could not load file '" + defaultFile.getName() + "': File not found."); - } - catch (Exception e) - { - this.addon.logError("Could not load objects " + defaultFile.getName() + " " + e.getMessage()); - } + return object; + } + catch (FileNotFoundException e) + { + this.addon.logError("Could not load file '" + defaultFile.getName() + "': File not found."); + } + catch (Exception e) + { + this.addon.logError("Could not load objects " + defaultFile.getName() + " " + e.getMessage()); + } - return null; - } + return null; + } - /** - * This method creates and adds to list all objects from default.json file. - * @return List of all objects from default.json that is with T instance. - */ - DefaultDataHolder loadWebObject(String downloadedObject) - { - return this.gson.fromJson(downloadedObject, DefaultDataHolder.class); - } + /** + * This method creates and adds to list all objects from default.json file. + * @return List of all objects from default.json that is with T instance. + */ + DefaultDataHolder loadWebObject(String downloadedObject) + { + return this.gson.fromJson(downloadedObject, DefaultDataHolder.class); + } - // --------------------------------------------------------------------- - // Section: Variables - // --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Variables + // --------------------------------------------------------------------- - /** - * Holds JSON builder object. - */ - private Gson gson; + /** + * Holds JSON builder object. + */ + private Gson gson; - /** - * Holds ChallengesAddon object. - */ - private ChallengesAddon addon; + /** + * Holds ChallengesAddon object. + */ + private ChallengesAddon addon; } - /** - * This is simple object that will allow to store all current challenges and levels - * in single file. - */ - private static final class DefaultDataHolder implements DataObject - { - /** - * Default constructor. Creates object with empty lists. - */ - DefaultDataHolder() - { - this.challengeList = Collections.emptyList(); - this.challengeLevelList = Collections.emptyList(); - this.version = ""; - } + /** + * This is simple object that will allow to store all current challenges and levels + * in single file. + */ + private static final class DefaultDataHolder implements DataObject + { + /** + * Default constructor. Creates object with empty lists. + */ + DefaultDataHolder() + { + this.challengeList = Collections.emptyList(); + this.challengeLevelList = Collections.emptyList(); + this.version = ""; + } - /** - * This method returns stored challenge list. - * @return list that contains default challenges. - */ - List getChallengeList() - { - return challengeList; - } + /** + * This method returns stored challenge list. + * @return list that contains default challenges. + */ + List getChallengeList() + { + return challengeList; + } - /** - * This method sets given list as default challenge list. - * @param challengeList new default challenge list. - */ - void setChallengeList(List challengeList) - { - this.challengeList = challengeList; - } + /** + * This method sets given list as default challenge list. + * @param challengeList new default challenge list. + */ + void setChallengeList(List challengeList) + { + this.challengeList = challengeList; + } - /** - * This method returns list of default challenge levels. - * @return List that contains default challenge levels. - */ - List getLevelList() - { - return challengeLevelList; - } + /** + * This method returns list of default challenge levels. + * @return List that contains default challenge levels. + */ + List getLevelList() + { + return challengeLevelList; + } - /** - * This method sets given list as default challenge level list. - * @param levelList new default challenge level list. - */ - void setLevelList(List levelList) - { - this.challengeLevelList = levelList; - } + /** + * This method sets given list as default challenge level list. + * @param levelList new default challenge level list. + */ + void setLevelList(List levelList) + { + this.challengeLevelList = levelList; + } - /** - * This method returns the version value. - * @return the value of version. - */ - public String getVersion() - { - return version; - } + /** + * This method returns the version value. + * @return the value of version. + */ + public String getVersion() + { + return version; + } - /** - * This method sets the version value. - * @param version the version new value. - * - */ - public void setVersion(String version) - { - this.version = version; - } + /** + * This method sets the version value. + * @param version the version new value. + * + */ + public void setVersion(String version) + { + this.version = version; + } - /** - * @return default.json - */ - @Override - public String getUniqueId() - { - return "default.json"; - } + /** + * @return default.json + */ + @Override + public String getUniqueId() + { + return "default.json"; + } - /** - * @param uniqueId - unique ID the uniqueId to set - */ - @Override - public void setUniqueId(String uniqueId) - { - // method not used. - } + /** + * @param uniqueId - unique ID the uniqueId to set + */ + @Override + public void setUniqueId(String uniqueId) + { + // method not used. + } - // --------------------------------------------------------------------- - // Section: Variables - // --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Variables + // --------------------------------------------------------------------- - /** - * Holds a list with default challenges. - */ - @Expose - private List challengeList; + /** + * Holds a list with default challenges. + */ + @Expose + private List challengeList; - /** - * Holds a list with default levels. - */ - @Expose - private List challengeLevelList; + /** + * Holds a list with default levels. + */ + @Expose + private List challengeLevelList; - /** - * Holds a variable that stores in which addon version file was made. - */ - @Expose - private String version; - } + /** + * Holds a variable that stores in which addon version file was made. + */ + @Expose + private String version; + } -// --------------------------------------------------------------------- -// Section: Variables -// --------------------------------------------------------------------- + // --------------------------------------------------------------------- + // Section: Variables + // --------------------------------------------------------------------- - private ChallengesAddon addon; + private ChallengesAddon addon; } \ No newline at end of file diff --git a/src/main/java/world/bentobox/challenges/ChallengesManager.java b/src/main/java/world/bentobox/challenges/ChallengesManager.java index 601d0ff..927bddf 100644 --- a/src/main/java/world/bentobox/challenges/ChallengesManager.java +++ b/src/main/java/world/bentobox/challenges/ChallengesManager.java @@ -265,13 +265,6 @@ public class ChallengesManager User user, boolean silent) { - if (challenge == null) - { - this.addon.logError( - "Tried to load NULL element from Database. One challenge is broken and will not work."); - return false; - } - if (this.challengeCacheData.containsKey(challenge.getUniqueId())) { if (!overwrite) @@ -333,13 +326,6 @@ public class ChallengesManager User user, boolean silent) { - if (level == null) - { - this.addon.logError( - "Tried to load NULL element from Database. One level is broken and will not work."); - return false; - } - if (!this.isValidLevel(level)) { if (user != null) diff --git a/src/main/java/world/bentobox/challenges/commands/ChallengesCommand.java b/src/main/java/world/bentobox/challenges/commands/ChallengesCommand.java index b378e14..7012c9b 100644 --- a/src/main/java/world/bentobox/challenges/commands/ChallengesCommand.java +++ b/src/main/java/world/bentobox/challenges/commands/ChallengesCommand.java @@ -2,6 +2,7 @@ package world.bentobox.challenges.commands; import java.util.List; +import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.user.User; import world.bentobox.challenges.ChallengesAddon; @@ -39,7 +40,9 @@ public class ChallengesCommand extends CompositeCommand // Show admin better explanation. if (user.isOp() || user.hasPermission(this.getPermissionPrefix() + "admin.challenges")) { - String topLabel = getIWM().getAddon(this.getWorld()).get().getAdminCommand().orElseGet(this::getParent).getTopLabel(); + String topLabel = getIWM().getAddon(this.getWorld()) + .map(GameModeAddon::getAdminCommand) + .map(optionalAdminCommand -> optionalAdminCommand.map(ac -> ac.getTopLabel()).orElse(this.getTopLabel())).orElse(this.getTopLabel()); user.sendMessage("challenges.errors.no-challenges-admin", "[command]", topLabel + " challenges"); } else diff --git a/src/main/java/world/bentobox/challenges/panel/admin/EditLoreGUI.java b/src/main/java/world/bentobox/challenges/panel/admin/EditLoreGUI.java index ac229fd..860de1a 100644 --- a/src/main/java/world/bentobox/challenges/panel/admin/EditLoreGUI.java +++ b/src/main/java/world/bentobox/challenges/panel/admin/EditLoreGUI.java @@ -12,6 +12,7 @@ import org.bukkit.Material; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; +import org.eclipse.jdt.annotation.Nullable; import world.bentobox.bentobox.api.panels.PanelItem; import world.bentobox.bentobox.api.panels.PanelListener; @@ -29,605 +30,609 @@ import world.bentobox.challenges.utils.GuiUtils; */ public class EditLoreGUI extends CommonGUI { - public EditLoreGUI(CommonGUI parent, LoreType loreType) - { - super(parent); - - this.lore = loreType; - this.activeValues = new ArrayList<>(); - - switch (this.lore) - { - case CHALLENGES: - - for (ChallengeLore lore : this.addon.getChallengesSettings().getChallengeLoreMessage()) - { - this.activeValues.add(lore.name()); - } - - break; - case LEVELS: - - for (LevelLore lore : this.addon.getChallengesSettings().getLevelLoreMessage()) - { - this.activeValues.add(lore.name()); - } - - break; - } - } - - - /** - * This is static call method for easier GUI opening. - * @param parent Parent GUI. - * @param loreType loreType that will be edited. - */ - public static void open(CommonGUI parent, LoreType loreType) - { - new EditLoreGUI(parent, loreType).build(); - } - - -// --------------------------------------------------------------------- -// Section: Methods -// --------------------------------------------------------------------- - - - /** - * This method builds panel that allows to change given number value. - */ - @Override - public void build() - { - PanelBuilder panelBuilder = new PanelBuilder(). - name(this.user.getTranslation("challenges.gui.title.admin.lore-edit")). - user(this.user). - listener(new CustomPanelListener()); - - GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); - - // Define all active buttons - panelBuilder.item(1, this.getButton(Button.SAVE)); - - panelBuilder.item(3, this.getButton(Button.ADD)); - panelBuilder.item(4, this.getButton(Button.REMOVE)); - - // TODO: Need 2 View Buttons - // One for closes / One for opened. -// panelBuilder.item(6, this.getButton(Button.VIEW)); - - panelBuilder.item(44, this.returnButton); - - // necessary as I have a border around this GUI - int currentIndex = 10; - - // Only 21 elements will be displayed. On porpoise! - for (int i = 0; i < this.activeValues.size() || i > 21; i++) - { - panelBuilder.item(currentIndex++, this.getLoreButton(this.activeValues.get(i))); - - // Border element - if (currentIndex % 9 == 8) - { - currentIndex += 2; - } - - // Just in case. Should never occur. - if (currentIndex % 9 == 0) - { - currentIndex++; - } - } - - panelBuilder.build(); - } - - - /** - * This method create button that does some functionality in current gui. - * @param button Button functionality. - * @return PanelItem. - */ - private PanelItem getButton(Button button) - { - ItemStack icon; - String name; - List description; - PanelItem.ClickHandler clickHandler; - - switch (button) - { - case SAVE: - { - name = this.user.getTranslation("challenges.gui.buttons.admin.save"); - description = Collections.emptyList(); - icon = new ItemStack(Material.COMMAND_BLOCK); - clickHandler = (panel, user, clickType, slot) -> { - - switch (this.lore) - { - case CHALLENGES: - { - List lore = this.activeValues.stream(). - map(ChallengeLore::valueOf). - collect(Collectors.toCollection(() -> new ArrayList<>(this.activeValues.size()))); - - this.addon.getChallengesSettings().setChallengeLoreMessage(lore); - - break; - } - case LEVELS: - { - List lore = this.activeValues.stream(). - map(LevelLore::valueOf). - collect(Collectors.toCollection(() -> new ArrayList<>(this.activeValues.size()))); - - this.addon.getChallengesSettings().setLevelLoreMessage(lore); - - break; - } - } - - // Save and return to parent gui. - this.parentGUI.build(); - - return true; - }; - break; - } - case ADD: - { - name = this.user.getTranslation("challenges.gui.buttons.admin.add"); - description = Collections.emptyList(); - icon = new ItemStack(Material.GREEN_STAINED_GLASS_PANE); - clickHandler = (panel, user, clickType, slot) -> { - new AddLoreElementGUI(element -> { - this.activeValues.add(element); - this.build(); - }); - - return true; - }; - - break; - } - case REMOVE: - { - name = this.user.getTranslation("challenges.gui.buttons.admin.remove-selected"); - description = Collections.emptyList(); - icon = new ItemStack(Material.RED_STAINED_GLASS_PANE); - clickHandler = (panel, user, clickType, slot) -> { - new RemoveLoreElementGUI((element, index) -> { - if (this.activeValues.get(index).equals(element)) - { - this.activeValues.remove(element); - } - - this.build(); - }); - - return true; - }; - - break; - } - case VIEW: - { - name = this.user.getTranslation("challenges.gui.buttons.admin.view"); - description = Collections.emptyList(); - icon = new ItemStack(Material.YELLOW_STAINED_GLASS_PANE); - clickHandler = (panel, user, clickType, slot) -> { - return true; - }; - - break; - } - default: - return null; - } - - return new PanelItemBuilder(). - icon(icon). - name(name). - description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). - glow(false). - clickHandler(clickHandler). - build(); - } - - - /** - * This method creates button for lore element. - * @param loreElement String that represents current lore element. - * @return PanelItem. - */ - private PanelItem getLoreButton(String loreElement) - { - switch (this.lore) - { - case CHALLENGES: - return this.getChallengeLoreButton(loreElement); - case LEVELS: - return this.getLevelLoreButton(loreElement); - default: - // this should never happen! - return null; - } - } - - - /** - * This method creates button for challenge lore element. - * @param loreElement String that represents current challenge lore element. - * @return PanelItem. - */ - private PanelItem getChallengeLoreButton(String loreElement) - { - Material icon; - String name = loreElement; - List description = new ArrayList<>(); - description.add(this.user.getTranslation(REFERENCE_DESCRIPTION + "lore." + loreElement.toLowerCase())); - - PanelItem.ClickHandler clickHandler = (panel, user1, clickType, slot) -> true; - - switch (ChallengeLore.valueOf(loreElement)) - { - case LEVEL: - { - icon = Material.DIRT; - break; - } - case STATUS: - { - icon = Material.LEVER; - break; - } - case COUNT: - { - icon = Material.REPEATER; - break; - } - case DESCRIPTION: - { - icon = Material.WRITTEN_BOOK; - break; - } - case WARNINGS: - { - icon = Material.LAVA_BUCKET; - break; - } - case ENVIRONMENT: - { - icon = Material.GLASS; - break; - } - case REQUIREMENTS: - { - icon = Material.HOPPER; - break; - } - case REWARD_TEXT: - { - icon = Material.PAPER; - break; - } - case REWARD_OTHER: - { - icon = Material.CHEST; - break; - } - case REWARD_ITEMS: - { - icon = Material.TRAPPED_CHEST; - break; - } - case REWARD_COMMANDS: - { - icon = Material.COMMAND_BLOCK; - break; - } - default: - { - icon = Material.BARRIER; - break; - } - } - - return new PanelItemBuilder(). - name(name). - icon(icon). - description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). - clickHandler(clickHandler). - glow(false). - build(); - } - - - /** - * This method creates button for challenge level lore element. - * @param loreElement String that represents current challenge level lore element. - * @return PanelItem. - */ - private PanelItem getLevelLoreButton(String loreElement) - { - Material icon; - String name = loreElement; - List description = new ArrayList<>(); - description.add(this.user.getTranslation(REFERENCE_DESCRIPTION + "lore." + loreElement.toLowerCase())); - - PanelItem.ClickHandler clickHandler = (panel, user1, clickType, slot) -> true; - - switch (LevelLore.valueOf(loreElement)) - { - case LEVEL_STATUS: - { - icon = Material.DIRT; - break; - } - case CHALLENGE_COUNT: - { - icon = Material.REPEATER; - break; - } - case UNLOCK_MESSAGE: - { - icon = Material.WRITTEN_BOOK; - break; - } - case WAIVER_AMOUNT: - { - icon = Material.COMPARATOR; - break; - } - case LEVEL_REWARD_TEXT: - { - icon = Material.PAPER; - break; - } - case LEVEL_REWARD_OTHER: - { - icon = Material.CHEST; - break; - } - case LEVEL_REWARD_ITEMS: - { - icon = Material.TRAPPED_CHEST; - break; - } - case LEVEL_REWARD_COMMANDS: - { - icon = Material.COMMAND_BLOCK; - break; - } - default: - { - icon = Material.BARRIER; - break; - } - } - - return new PanelItemBuilder(). - name(name). - icon(icon). - description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). - clickHandler(clickHandler). - glow(false). - build(); - } - - -// --------------------------------------------------------------------- -// Section: Select GUI -// --------------------------------------------------------------------- - - - /** - * This class opens new GUI that add an element from all available lore values. - */ - private class AddLoreElementGUI - { - private AddLoreElementGUI(Consumer selectedElement) - { - PanelBuilder panelBuilder = new PanelBuilder(). - name(EditLoreGUI.this.user.getTranslation("challenges.gui.title.admin.lore-add")). - user(EditLoreGUI.this.user); - - GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); - - int currentIndex = 10; - - List values = new ArrayList<>(); - - // Populate list with all elements. - switch (EditLoreGUI.this.lore) - { - case CHALLENGES: - for (ChallengeLore value : ChallengeLore.values()) - { - values.add(value.name()); - } - break; - case LEVELS: - for (LevelLore value : LevelLore.values()) - { - values.add(value.name()); - } - break; - } - - for (String value : values) - { - PanelItem item = EditLoreGUI.this.getLoreButton(value); - - item.setClickHandler((panel, user1, clickType, slot) -> { - selectedElement.accept(value); - return true; - }); - - panelBuilder.item(currentIndex++, item); - - // Border element - if (currentIndex % 9 == 8) - { - currentIndex += 2; - } - - // Just in case. Should never occur. - if (currentIndex % 9 == 0) - { - currentIndex++; - } - - // Just in case. Should never occur. - if (currentIndex > 35) - { - break; - } - } - - panelBuilder.build(); - } - } - - - /** - * This class opens new GUI that remove an element from all available lore values. - */ - private class RemoveLoreElementGUI - { - private RemoveLoreElementGUI(BiConsumer selectedElement) - { - PanelBuilder panelBuilder = new PanelBuilder(). - name(EditLoreGUI.this.user.getTranslation("challenges.gui.title.admin.lore-remove")). - user(EditLoreGUI.this.user); - - GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); - - int currentIndex = 10; - - List values = EditLoreGUI.this.activeValues; - - for (int i = 0; i < values.size(); i++) - { - final int counter = i; - - String value = values.get(counter); - PanelItem item = EditLoreGUI.this.getLoreButton(value); - - item.setClickHandler((panel, user1, clickType, slot) -> { - selectedElement.accept(value, counter); - return true; - }); - - panelBuilder.item(currentIndex++, item); - - // Border element - if (currentIndex % 9 == 8) - { - currentIndex += 2; - } - - // Just in case. Should never occur. - if (currentIndex % 9 == 0) - { - currentIndex++; - } - - // Just in case. Should never occur. - if (currentIndex > 35) - { - break; - } - } - - panelBuilder.build(); - } - } - - -// --------------------------------------------------------------------- -// Section: Private classes -// --------------------------------------------------------------------- - - - /** - * This CustomPanelListener allows to move items in current panel. - */ - private class CustomPanelListener implements PanelListener - { - @Override - public void setup() - { - } - - - @Override - public void onInventoryClose(InventoryCloseEvent inventoryCloseEvent) - { - } - - - @Override - public void onInventoryClick(User user, InventoryClickEvent event) - { - // First row of elements should be ignored, as it contains buttons and blocked slots. - event.setCancelled(event.getRawSlot() < 9 || - event.getRawSlot() < 35 || - event.getRawSlot() % 9 == 0 || - event.getRawSlot() % 9 == 8); - } - } + public EditLoreGUI(CommonGUI parent, LoreType loreType) + { + super(parent); + + this.lore = loreType; + this.activeValues = new ArrayList<>(); + + switch (this.lore) + { + case CHALLENGES: + + for (ChallengeLore lore : this.addon.getChallengesSettings().getChallengeLoreMessage()) + { + this.activeValues.add(lore.name()); + } + + break; + case LEVELS: + + for (LevelLore lore : this.addon.getChallengesSettings().getLevelLoreMessage()) + { + this.activeValues.add(lore.name()); + } + + break; + } + } + + + /** + * This is static call method for easier GUI opening. + * @param parent Parent GUI. + * @param loreType loreType that will be edited. + */ + public static void open(CommonGUI parent, LoreType loreType) + { + new EditLoreGUI(parent, loreType).build(); + } + + + // --------------------------------------------------------------------- + // Section: Methods + // --------------------------------------------------------------------- + + + /** + * This method builds panel that allows to change given number value. + */ + @Override + public void build() + { + PanelBuilder panelBuilder = new PanelBuilder(). + name(this.user.getTranslation("challenges.gui.title.admin.lore-edit")). + user(this.user). + listener(new CustomPanelListener()); + + GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); + + // Define all active buttons + panelBuilder.item(1, this.getButton(Button.SAVE)); + + panelBuilder.item(3, this.getButton(Button.ADD)); + panelBuilder.item(4, this.getButton(Button.REMOVE)); + + // TODO: Need 2 View Buttons + // One for closes / One for opened. + // panelBuilder.item(6, this.getButton(Button.VIEW)); + + panelBuilder.item(44, this.returnButton); + + // necessary as I have a border around this GUI + int currentIndex = 10; + + // Only 21 elements will be displayed. On porpoise! + for (int i = 0; i < this.activeValues.size() || i > 21; i++) + { + panelBuilder.item(currentIndex++, this.getLoreButton(this.activeValues.get(i))); + + // Border element + if (currentIndex % 9 == 8) + { + currentIndex += 2; + } + + // Just in case. Should never occur. + if (currentIndex % 9 == 0) + { + currentIndex++; + } + } + + panelBuilder.build(); + } + + + /** + * This method create button that does some functionality in current gui. + * @param button Button functionality. + * @return PanelItem. + */ + private PanelItem getButton(Button button) + { + ItemStack icon; + String name; + List description; + PanelItem.ClickHandler clickHandler; + + switch (button) + { + case SAVE: + { + name = this.user.getTranslation("challenges.gui.buttons.admin.save"); + description = Collections.emptyList(); + icon = new ItemStack(Material.COMMAND_BLOCK); + clickHandler = (panel, user, clickType, slot) -> { + + switch (this.lore) + { + case CHALLENGES: + { + List lore = this.activeValues.stream(). + map(ChallengeLore::valueOf). + collect(Collectors.toCollection(() -> new ArrayList<>(this.activeValues.size()))); + + this.addon.getChallengesSettings().setChallengeLoreMessage(lore); + + break; + } + case LEVELS: + { + List lore = this.activeValues.stream(). + map(LevelLore::valueOf). + collect(Collectors.toCollection(() -> new ArrayList<>(this.activeValues.size()))); + + this.addon.getChallengesSettings().setLevelLoreMessage(lore); + + break; + } + } + + // Save and return to parent gui. + this.parentGUI.build(); + + return true; + }; + break; + } + case ADD: + { + name = this.user.getTranslation("challenges.gui.buttons.admin.add"); + description = Collections.emptyList(); + icon = new ItemStack(Material.GREEN_STAINED_GLASS_PANE); + clickHandler = (panel, user, clickType, slot) -> { + new AddLoreElementGUI(element -> { + this.activeValues.add(element); + this.build(); + }); + + return true; + }; + + break; + } + case REMOVE: + { + name = this.user.getTranslation("challenges.gui.buttons.admin.remove-selected"); + description = Collections.emptyList(); + icon = new ItemStack(Material.RED_STAINED_GLASS_PANE); + clickHandler = (panel, user, clickType, slot) -> { + new RemoveLoreElementGUI((element, index) -> { + if (this.activeValues.get(index).equals(element)) + { + this.activeValues.remove(element); + } + + this.build(); + }); + + return true; + }; + + break; + } + case VIEW: + { + name = this.user.getTranslation("challenges.gui.buttons.admin.view"); + description = Collections.emptyList(); + icon = new ItemStack(Material.YELLOW_STAINED_GLASS_PANE); + clickHandler = (panel, user, clickType, slot) -> { + return true; + }; + + break; + } + default: + return null; + } + + return new PanelItemBuilder(). + icon(icon). + name(name). + description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). + glow(false). + clickHandler(clickHandler). + build(); + } + + + /** + * This method creates button for lore element. + * @param loreElement String that represents current lore element. + * @return PanelItem. + */ + @Nullable + private PanelItem getLoreButton(String loreElement) + { + switch (this.lore) + { + case CHALLENGES: + return this.getChallengeLoreButton(loreElement); + case LEVELS: + return this.getLevelLoreButton(loreElement); + default: + // this should never happen! + return null; + } + } + + + /** + * This method creates button for challenge lore element. + * @param loreElement String that represents current challenge lore element. + * @return PanelItem. + */ + private PanelItem getChallengeLoreButton(String loreElement) + { + Material icon; + String name = loreElement; + List description = new ArrayList<>(); + description.add(this.user.getTranslation(REFERENCE_DESCRIPTION + "lore." + loreElement.toLowerCase())); + + PanelItem.ClickHandler clickHandler = (panel, user1, clickType, slot) -> true; + + switch (ChallengeLore.valueOf(loreElement)) + { + case LEVEL: + { + icon = Material.DIRT; + break; + } + case STATUS: + { + icon = Material.LEVER; + break; + } + case COUNT: + { + icon = Material.REPEATER; + break; + } + case DESCRIPTION: + { + icon = Material.WRITTEN_BOOK; + break; + } + case WARNINGS: + { + icon = Material.LAVA_BUCKET; + break; + } + case ENVIRONMENT: + { + icon = Material.GLASS; + break; + } + case REQUIREMENTS: + { + icon = Material.HOPPER; + break; + } + case REWARD_TEXT: + { + icon = Material.PAPER; + break; + } + case REWARD_OTHER: + { + icon = Material.CHEST; + break; + } + case REWARD_ITEMS: + { + icon = Material.TRAPPED_CHEST; + break; + } + case REWARD_COMMANDS: + { + icon = Material.COMMAND_BLOCK; + break; + } + default: + { + icon = Material.BARRIER; + break; + } + } + + return new PanelItemBuilder(). + name(name). + icon(icon). + description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). + clickHandler(clickHandler). + glow(false). + build(); + } + + + /** + * This method creates button for challenge level lore element. + * @param loreElement String that represents current challenge level lore element. + * @return PanelItem. + */ + private PanelItem getLevelLoreButton(String loreElement) + { + Material icon; + String name = loreElement; + List description = new ArrayList<>(); + description.add(this.user.getTranslation(REFERENCE_DESCRIPTION + "lore." + loreElement.toLowerCase())); + + PanelItem.ClickHandler clickHandler = (panel, user1, clickType, slot) -> true; + + switch (LevelLore.valueOf(loreElement)) + { + case LEVEL_STATUS: + { + icon = Material.DIRT; + break; + } + case CHALLENGE_COUNT: + { + icon = Material.REPEATER; + break; + } + case UNLOCK_MESSAGE: + { + icon = Material.WRITTEN_BOOK; + break; + } + case WAIVER_AMOUNT: + { + icon = Material.COMPARATOR; + break; + } + case LEVEL_REWARD_TEXT: + { + icon = Material.PAPER; + break; + } + case LEVEL_REWARD_OTHER: + { + icon = Material.CHEST; + break; + } + case LEVEL_REWARD_ITEMS: + { + icon = Material.TRAPPED_CHEST; + break; + } + case LEVEL_REWARD_COMMANDS: + { + icon = Material.COMMAND_BLOCK; + break; + } + default: + { + icon = Material.BARRIER; + break; + } + } + + return new PanelItemBuilder(). + name(name). + icon(icon). + description(GuiUtils.stringSplit(description, this.addon.getChallengesSettings().getLoreLineLength())). + clickHandler(clickHandler). + glow(false). + build(); + } + + + // --------------------------------------------------------------------- + // Section: Select GUI + // --------------------------------------------------------------------- + + + /** + * This class opens new GUI that add an element from all available lore values. + */ + private class AddLoreElementGUI + { + private AddLoreElementGUI(Consumer selectedElement) + { + PanelBuilder panelBuilder = new PanelBuilder(). + name(EditLoreGUI.this.user.getTranslation("challenges.gui.title.admin.lore-add")). + user(EditLoreGUI.this.user); + + GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); + + int currentIndex = 10; + + List values = new ArrayList<>(); + + // Populate list with all elements. + switch (EditLoreGUI.this.lore) + { + case CHALLENGES: + for (ChallengeLore value : ChallengeLore.values()) + { + values.add(value.name()); + } + break; + case LEVELS: + for (LevelLore value : LevelLore.values()) + { + values.add(value.name()); + } + break; + } + + for (String value : values) + { + PanelItem item = EditLoreGUI.this.getLoreButton(value); + if (item != null) { + item.setClickHandler((panel, user1, clickType, slot) -> { + selectedElement.accept(value); + return true; + }); + + panelBuilder.item(currentIndex++, item); + + + // Border element + if (currentIndex % 9 == 8) + { + currentIndex += 2; + } + + // Just in case. Should never occur. + if (currentIndex % 9 == 0) + { + currentIndex++; + } + + // Just in case. Should never occur. + if (currentIndex > 35) + { + break; + } + } + } + + panelBuilder.build(); + } + } + + + /** + * This class opens new GUI that remove an element from all available lore values. + */ + private class RemoveLoreElementGUI + { + private RemoveLoreElementGUI(BiConsumer selectedElement) + { + PanelBuilder panelBuilder = new PanelBuilder(). + name(EditLoreGUI.this.user.getTranslation("challenges.gui.title.admin.lore-remove")). + user(EditLoreGUI.this.user); + + GuiUtils.fillBorder(panelBuilder, 5, Material.MAGENTA_STAINED_GLASS_PANE); + + int currentIndex = 10; + + List values = EditLoreGUI.this.activeValues; + + for (int i = 0; i < values.size(); i++) + { + final int counter = i; + + String value = values.get(counter); + PanelItem item = EditLoreGUI.this.getLoreButton(value); + if (item != null) { + item.setClickHandler((panel, user1, clickType, slot) -> { + selectedElement.accept(value, counter); + return true; + }); + + panelBuilder.item(currentIndex++, item); + + // Border element + if (currentIndex % 9 == 8) + { + currentIndex += 2; + } + + // Just in case. Should never occur. + if (currentIndex % 9 == 0) + { + currentIndex++; + } + + // Just in case. Should never occur. + if (currentIndex > 35) + { + break; + } + } + } + + panelBuilder.build(); + } + } + + + // --------------------------------------------------------------------- + // Section: Private classes + // --------------------------------------------------------------------- + + + /** + * This CustomPanelListener allows to move items in current panel. + */ + private class CustomPanelListener implements PanelListener + { + @Override + public void setup() + { + } + + + @Override + public void onInventoryClose(InventoryCloseEvent inventoryCloseEvent) + { + } + + + @Override + public void onInventoryClick(User user, InventoryClickEvent event) + { + // First row of elements should be ignored, as it contains buttons and blocked slots. + event.setCancelled(event.getRawSlot() < 9 || + event.getRawSlot() < 35 || + event.getRawSlot() % 9 == 0 || + event.getRawSlot() % 9 == 8); + } + } + + + // --------------------------------------------------------------------- + // Section: Enums + // --------------------------------------------------------------------- + + + /** + * This enum holds all button values in current gui. + */ + private enum Button + { + SAVE, + ADD, + REMOVE, + VIEW, + RETURN + } + + + /** + * This enum holds which Lore is edited with current GUI. + */ + public enum LoreType + { + CHALLENGES, + LEVELS, + } + + + // --------------------------------------------------------------------- + // Section: Variables + // --------------------------------------------------------------------- + + /** + * Lore that will be edited with current GUI. + */ + private final LoreType lore; + + /** + * List of lore elements that are currently enabled. + */ + private List activeValues; + + + // --------------------------------------------------------------------- + // Section: Constants + // --------------------------------------------------------------------- - -// --------------------------------------------------------------------- -// Section: Enums -// --------------------------------------------------------------------- - - - /** - * This enum holds all button values in current gui. - */ - private enum Button - { - SAVE, - ADD, - REMOVE, - VIEW, - RETURN - } - - - /** - * This enum holds which Lore is edited with current GUI. - */ - public enum LoreType - { - CHALLENGES, - LEVELS, - } - - -// --------------------------------------------------------------------- -// Section: Variables -// --------------------------------------------------------------------- - - /** - * Lore that will be edited with current GUI. - */ - private final LoreType lore; - - /** - * List of lore elements that are currently enabled. - */ - private List activeValues; - - -// --------------------------------------------------------------------- -// Section: Constants -// --------------------------------------------------------------------- - - - private final static String REFERENCE_DESCRIPTION = "challenges.gui.descriptions.admin."; + + private final static String REFERENCE_DESCRIPTION = "challenges.gui.descriptions.admin."; } diff --git a/src/main/java/world/bentobox/challenges/tasks/TryToComplete.java b/src/main/java/world/bentobox/challenges/tasks/TryToComplete.java index 5e53e6e..dc8edb2 100644 --- a/src/main/java/world/bentobox/challenges/tasks/TryToComplete.java +++ b/src/main/java/world/bentobox/challenges/tasks/TryToComplete.java @@ -349,7 +349,7 @@ public class TryToComplete if (this.addon.isEconomyProvided()) { this.addon.getEconomyProvider().deposit(this.user, - this.challenge.getRepeatMoneyReward() * rewardFactor); + (double)this.challenge.getRepeatMoneyReward() * rewardFactor); } // Experience Repeat Reward diff --git a/src/main/java/world/bentobox/challenges/web/WebManager.java b/src/main/java/world/bentobox/challenges/web/WebManager.java index d2545f6..702d7ef 100644 --- a/src/main/java/world/bentobox/challenges/web/WebManager.java +++ b/src/main/java/world/bentobox/challenges/web/WebManager.java @@ -126,7 +126,6 @@ public class WebManager * @param user User who inits request. * @param world Target world where challenges should be loaded. * @param entry Entry that contains information about requested object. - * @return {@code true} if request was successful, {@code false} otherwise. */ public void requestEntryGitHubData(User user, World world, LibraryEntry entry) { diff --git a/src/test/java/world/bentobox/challenges/ChallengesAddonTest.java b/src/test/java/world/bentobox/challenges/ChallengesAddonTest.java deleted file mode 100644 index 60b88f9..0000000 --- a/src/test/java/world/bentobox/challenges/ChallengesAddonTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package world.bentobox.challenges; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Logger; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemFactory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.plugin.PluginManager; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionType; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.modules.junit4.PowerMockRunner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import world.bentobox.challenges.database.object.Challenge; -import world.bentobox.challenges.database.object.Challenge.ChallengeType; - -/** - * @author tastybento - * - */ -@RunWith(PowerMockRunner.class) -public class ChallengesAddonTest { - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - Server server = mock(Server.class); - World world = mock(World.class); - world = mock(World.class); - Mockito.when(server.getLogger()).thenReturn(Logger.getAnonymousLogger()); - Mockito.when(server.getWorld("world")).thenReturn(world); - Mockito.when(server.getVersion()).thenReturn("BSB_Mocking"); - - PluginManager pluginManager = mock(PluginManager.class); - when(server.getPluginManager()).thenReturn(pluginManager); - - ItemFactory itemFactory = mock(ItemFactory.class); - when(server.getItemFactory()).thenReturn(itemFactory); - - Bukkit.setServer(server); - - PotionMeta potionMeta = mock(PotionMeta.class); - when(itemFactory.getItemMeta(any())).thenReturn(potionMeta); - - OfflinePlayer offlinePlayer = mock(OfflinePlayer.class); - when(Bukkit.getOfflinePlayer(any(UUID.class))).thenReturn(offlinePlayer); - when(offlinePlayer.getName()).thenReturn("tastybento"); - - when(Bukkit.getItemFactory()).thenReturn(itemFactory); - when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger()); - - } - - @Test - public void test() { - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - Challenge challenges = new Challenge(); - challenges.setChallengeType(ChallengeType.ISLAND); - Map map = new HashMap<>(); - map.put(Material.DIRT, 5); - map.put(Material.ACACIA_FENCE_GATE, 3); - challenges.setRequiredBlocks(map); - challenges.setIcon(new ItemStack(Material.ACACIA_FENCE_GATE)); - List requiredItems = new ArrayList<>(); - ItemStack result = new ItemStack(Material.POTION, 55); - ItemStack result2 = new ItemStack(Material.SPLASH_POTION, 22); - ItemStack result3 = new ItemStack(Material.LINGERING_POTION, 11); - - PotionMeta potionMeta = (PotionMeta) result.getItemMeta(); - PotionData potionData = new PotionData(PotionType.FIRE_RESISTANCE, true, false); - potionMeta.setBasePotionData(potionData); - result.setItemMeta(potionMeta); - - PotionMeta potionMeta2 = (PotionMeta) result2.getItemMeta(); - PotionData potionData2 = new PotionData(PotionType.SPEED, true, false); - potionMeta2.setBasePotionData(potionData2); - potionMeta2.addEnchant(Enchantment.BINDING_CURSE, 1, true); - result2.setItemMeta(potionMeta2); - - requiredItems.add(result); - requiredItems.add(result2); - requiredItems.add(result3); - challenges.setRequiredItems(requiredItems); - String json = gson.toJson(challenges); - - Logger.getAnonymousLogger().info(json); - - } - -}