Fix code smells from sonarcloud analysis

This commit is contained in:
tastybento 2019-10-25 16:30:14 -07:00
parent c53fea9f6a
commit 96d94fa16e
8 changed files with 968 additions and 1088 deletions

View File

@ -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();

View File

@ -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 <code>true</code> if everything was successful, otherwise <code>false</code>.
*/
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 <code>true</code> if everything was successful, otherwise <code>false</code>.
*/
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 <code>true</code> if everything was successful, otherwise <code>false</code>
* @param overwrite indicates if existing default.json file can be overwritten.
* @return <code>true</code> if everything was successful, otherwise <code>false</code>
*/
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<Challenge> 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<Challenge> 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<ChallengeLevel> 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<ChallengeLevel> 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<Challenge> getChallengeList()
{
return challengeList;
}
/**
* This method returns stored challenge list.
* @return list that contains default challenges.
*/
List<Challenge> getChallengeList()
{
return challengeList;
}
/**
* This method sets given list as default challenge list.
* @param challengeList new default challenge list.
*/
void setChallengeList(List<Challenge> challengeList)
{
this.challengeList = challengeList;
}
/**
* This method sets given list as default challenge list.
* @param challengeList new default challenge list.
*/
void setChallengeList(List<Challenge> challengeList)
{
this.challengeList = challengeList;
}
/**
* This method returns list of default challenge levels.
* @return List that contains default challenge levels.
*/
List<ChallengeLevel> getLevelList()
{
return challengeLevelList;
}
/**
* This method returns list of default challenge levels.
* @return List that contains default challenge levels.
*/
List<ChallengeLevel> getLevelList()
{
return challengeLevelList;
}
/**
* This method sets given list as default challenge level list.
* @param levelList new default challenge level list.
*/
void setLevelList(List<ChallengeLevel> levelList)
{
this.challengeLevelList = levelList;
}
/**
* This method sets given list as default challenge level list.
* @param levelList new default challenge level list.
*/
void setLevelList(List<ChallengeLevel> 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<Challenge> challengeList;
/**
* Holds a list with default challenges.
*/
@Expose
private List<Challenge> challengeList;
/**
* Holds a list with default levels.
*/
@Expose
private List<ChallengeLevel> challengeLevelList;
/**
* Holds a list with default levels.
*/
@Expose
private List<ChallengeLevel> 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;
}

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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)
{

View File

@ -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<Material, Integer> 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<ItemStack> 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);
}
}