Added logging methods to BSkyBlock to avoid plugin.getLogger()

plugin.getLogger() is a final class and so cannot be mocked. It was
making development of tests very hard. By making three logging methods
in BSkyBlock.java, they default to do nothing when BSkyBlock is mocked.
Previously, every time there was a use of logger in testing it was
throwing NPE's because plugin.getLogger() was returning null and the
getLogger() method could not be made not null by mocking because it was
final (in JavaPlugin).
This commit is contained in:
tastybento 2018-04-28 13:02:15 +09:00
parent 67d86cc1d9
commit aad5239ba3
25 changed files with 221 additions and 151 deletions

View File

@ -65,14 +65,14 @@ public class BSkyBlock extends JavaPlugin {
try {
settings = settings.loadSettings();
} catch (Exception e) {
getLogger().severe("Settings could not be loaded " + e.getMessage());
logError("Settings could not be loaded " + e.getMessage());
}
// Save a backup of settings to the database so it can be checked next time
try {
settings.saveBackup();
} catch (Exception e) {
getLogger().severe("Settings backup could not be saved" + e.getMessage());
logError("Settings backup could not be saved" + e.getMessage());
}
// Start Database managers
@ -287,4 +287,16 @@ public class BSkyBlock extends JavaPlugin {
public HeadGetter getHeadGetter() {
return headGetter;
}
public void log(String string) {
getLogger().info(() -> string);
}
public void logError(String error) {
getLogger().severe(() -> error);
}
public void logWarning(String warning) {
getLogger().warning(warning);
}
}

View File

@ -49,7 +49,7 @@ public class AddonClassLoader extends URLClassLoader {
throw new InvalidAddonFormatException("Packages declaration cannot start with 'us.tastybento'");
}
} catch (ClassNotFoundException e) {
BSkyBlock.getInstance().getLogger().severe("Could not load '" + path.getName() + "' in folder '" + path.getParent() + "' - invalid addon.yml");
BSkyBlock.getInstance().logError("Could not load '" + path.getName() + "' in folder '" + path.getParent() + "' - invalid addon.yml");
throw new InvalidDescriptionException("Invalid addon.yml");
}

View File

@ -40,7 +40,7 @@ public class PlaceholderHandler {
apis.add(internal);
} catch (Exception e){
// Should never happen.
plugin.getLogger().severe("Failed to load default placeholder API");
plugin.logError("Failed to load default placeholder API");
}
// Load hooks
@ -50,13 +50,13 @@ public class PlaceholderHandler {
Class<?> clazz = Class.forName(PACKAGE + hook + "PlaceholderImpl");
PlaceholderAPIInterface api = (PlaceholderAPIInterface)clazz.newInstance();
if(api.register(plugin)){
plugin.getLogger().info(() -> "Hooked placeholders into " + hook); // since Java 8, we can use Supplier , which will be evaluated lazily
plugin.log("Hooked placeholders into " + hook); // since Java 8, we can use Supplier , which will be evaluated lazily
apis.add(api);
} else {
plugin.getLogger().info(() -> "Failed to hook placeholders into " + hook);
plugin.log("Failed to hook placeholders into " + hook);
}
} catch (Exception e){
plugin.getLogger().info(() -> "Failed to hook placeholders into " + hook);
plugin.log("Failed to hook placeholders into " + hook);
}
}
}

View File

@ -43,6 +43,9 @@ public class IslandCommand extends CompositeCommand {
*/
@Override
public boolean execute(User user, List<String> args) {
if (user == null) {
return false;
}
// If this player does not have an island, create one
if (!getPlugin().getIslands().hasIsland(user.getUniqueId())) {
getSubCommand("create").ifPresent(createCmd -> createCmd.execute(user, new ArrayList<>()));

View File

@ -60,7 +60,7 @@ public class IslandCreateCommand extends CompositeCommand {
.reason(Reason.CREATE)
.build();
} catch (IOException e) {
getPlugin().getLogger().severe("Could not create island for player. " + e.getMessage());
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage("commands.island.create.unable-create-island");
}
}

View File

@ -46,18 +46,9 @@ public class IslandResetCommand extends CompositeCommand {
player.setGameMode(GameMode.SPECTATOR);
// Get the player's old island
Island oldIsland = getIslands().getIsland(player.getUniqueId());
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: old island is at " + oldIsland.getCenter().getBlockX() + "," + oldIsland.getCenter().getBlockZ());
}
// Remove them from this island (it still exists and will be deleted later)
getIslands().removePlayer(player.getUniqueId());
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: old island's owner is " + oldIsland.getOwner());
}
// Create new island and then delete the old one
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: making new island ");
}
try {
NewIsland.builder()
.player(player)
@ -65,7 +56,7 @@ public class IslandResetCommand extends CompositeCommand {
.oldIsland(oldIsland)
.build();
} catch (IOException e) {
getPlugin().getLogger().severe("Could not create island for player. " + e.getMessage());
getPlugin().logError("Could not create island for player. " + e.getMessage());
user.sendMessage("commands.island.create.unable-create-island");
}
return true;

View File

@ -92,8 +92,7 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
if (range != island.getProtectionRange()) {
user.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
target.sendMessage("commands.admin.setrange.range-updated", "[number]", String.valueOf(range));
getPlugin().getLogger().info(
"Makeleader: Island protection range changed from " + island.getProtectionRange() + " to "
getPlugin().log("Makeleader: Island protection range changed from " + island.getProtectionRange() + " to "
+ range + " for " + user.getName() + " due to permission.");
}
island.setProtectionRange(range);

View File

@ -4,7 +4,7 @@ import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
/**
* An abstract class that handles insert/select-operations into/from a database
@ -27,7 +27,7 @@ public abstract class AbstractDatabaseHandler<T> {
*/
protected DatabaseConnecter databaseConnecter;
protected Plugin plugin;
protected BSkyBlock plugin;
/**
@ -40,7 +40,7 @@ public abstract class AbstractDatabaseHandler<T> {
* Contains the settings to create a connection to the database
* like host/port/database/user/password
*/
protected AbstractDatabaseHandler(Plugin plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
protected AbstractDatabaseHandler(BSkyBlock plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
this.plugin = plugin;
this.databaseConnecter = databaseConnecter;
this.dataObject = type;

View File

@ -3,8 +3,7 @@ package us.tastybento.bskyblock.database.flatfile;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.database.DatabaseConnecter;
/**
@ -17,7 +16,7 @@ import us.tastybento.bskyblock.database.DatabaseConnecter;
public class ConfigHandler<T> extends FlatFileDatabaseHandler<T> {
public ConfigHandler(Plugin plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
public ConfigHandler(BSkyBlock plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
super(plugin, type, databaseConnecter);
}

View File

@ -14,20 +14,19 @@ import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.database.DatabaseConnecter;
import us.tastybento.bskyblock.database.DatabaseConnectionSettingsImpl;
public class FlatFileDatabaseConnecter implements DatabaseConnecter {
private static final int MAX_LOOPS = 100;
private static final String DATABASE_FOLDER_NAME = "database";
private Plugin plugin;
private BSkyBlock plugin;
private File dataFolder;
public FlatFileDatabaseConnecter(Plugin plugin) {
public FlatFileDatabaseConnecter(BSkyBlock plugin) {
this.plugin = plugin;
dataFolder = new File(plugin.getDataFolder(), DATABASE_FOLDER_NAME);
}
@ -58,15 +57,15 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
config = new YamlConfiguration();
config.load(yamlFile);
} catch (Exception e) {
Bukkit.getLogger().severe("Could not load yaml file from database " + tableName + " " + fileName + " " + e.getMessage());
plugin.logError("Could not load yaml file from database " + tableName + " " + fileName + " " + e.getMessage());
}
} else {
// Create the missing file
config = new YamlConfiguration();
plugin.getLogger().info("No " + fileName + " found. Creating it...");
plugin.log("No " + fileName + " found. Creating it...");
try {
if (plugin.getResource(fileName) != null) {
plugin.getLogger().info("Using default found in jar file.");
plugin.log("Using default found in jar file.");
plugin.saveResource(fileName, false);
config = new YamlConfiguration();
config.load(yamlFile);
@ -74,7 +73,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
config.save(yamlFile);
}
} catch (Exception e) {
plugin.getLogger().severe("Could not create the " + fileName + " file!");
plugin.logError("Could not create the " + fileName + " file!");
}
}
return config;
@ -96,7 +95,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
try {
yamlConfig.save(file);
} catch (Exception e) {
Bukkit.getLogger().severe("Could not save yaml file to database " + tableName + " " + fileName + " " + e.getMessage());
plugin.logError("Could not save yaml file to database " + tableName + " " + fileName + " " + e.getMessage());
return;
}
if (commentMap != null && !commentMap.isEmpty()) {
@ -134,7 +133,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
Files.write(commentedFile.toPath(), (Iterable<String>)newFile.stream()::iterator);
Files.move(commentedFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e1) {
plugin.getLogger().severe(() -> "Could not comment config file " + file.getName() + " " + e1.getMessage());
plugin.logError("Could not comment config file " + file.getName() + " " + e1.getMessage());
}
}

View File

@ -23,8 +23,8 @@ import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.Constants.GameType;
import us.tastybento.bskyblock.api.configuration.ConfigComment;
@ -50,7 +50,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
private static final String DATABASE_FOLDER_NAME = "database";
protected boolean configFlag;
public FlatFileDatabaseHandler(Plugin plugin, Class<T> type, DatabaseConnecter dbConnecter) {
public FlatFileDatabaseHandler(BSkyBlock plugin, Class<T> type, DatabaseConnecter dbConnecter) {
super(plugin, type, dbConnecter);
}
@ -287,7 +287,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try {
config.set(storageLocation, ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).deserialize(value));
} catch (InstantiationException e) {
plugin.getLogger().severe(() -> "Could not instatiate adapter " + adapterNotation.value().getName() + " " + e.getMessage());
plugin.logError("Could not instatiate adapter " + adapterNotation.value().getName() + " " + e.getMessage());
}
// We are done here
continue fields;
@ -419,14 +419,14 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
} catch (Exception e) {
// This value does not exist - probably admin typed it wrongly
// Show what is available and pick one at random
plugin.getLogger().severe("Error in YML file: " + value + " is not a valid value in the enum " + clazz.getCanonicalName() + "!");
plugin.getLogger().severe("Options are : ");
plugin.logError("Error in YML file: " + value + " is not a valid value in the enum " + clazz.getCanonicalName() + "!");
plugin.logError("Options are : ");
boolean isSet = false;
for (Field fields : enumClass.getFields()) {
plugin.getLogger().severe(fields.getName());
plugin.logError(fields.getName());
if (!isSet && !((String)value).isEmpty() && fields.getName().substring(0, 1).equals(((String)value).substring(0, 1))) {
value = Enum.valueOf(enumClass, fields.getName());
plugin.getLogger().severe("Setting to " + fields.getName() + " because it starts with the same letter");
plugin.logError("Setting to " + fields.getName() + " because it starts with the same letter");
isSet = true;
}
}
@ -452,7 +452,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try {
Files.delete(file.toPath());
} catch (IOException e) {
plugin.getLogger().severe(() -> "Could not delete yaml database object! " + file.getName() + " - " + e.getMessage());
plugin.logError("Could not delete yaml database object! " + file.getName() + " - " + e.getMessage());
}
}
}

View File

@ -12,8 +12,8 @@ public class MongoDBDatabase extends BSBDbSetup{
BSkyBlock plugin = BSkyBlock.getInstance();
// Check if the MongoDB plugin exists
if (plugin.getServer().getPluginManager().getPlugin("BsbMongo") == null) {
plugin.getLogger().severe("You must install BsbMongo plugin for MongoDB support!");
plugin.getLogger().severe("See: https://github.com/tastybento/bsbMongo/releases/");
plugin.logError("You must install BsbMongo plugin for MongoDB support!");
plugin.logError("See: https://github.com/tastybento/bsbMongo/releases/");
plugin.getServer().getPluginManager().disablePlugin(plugin);
return null;
}

View File

@ -115,7 +115,7 @@ public class MongoDBDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@Override
public void saveObject(T instance) {
if (!(instance instanceof DataObject)) {
plugin.getLogger().severe(() -> "This class is not a DataObject: " + instance.getClass().getName());
plugin.logError("This class is not a DataObject: " + instance.getClass().getName());
return;
}
DataObject dataObj = (DataObject)instance;
@ -133,20 +133,20 @@ public class MongoDBDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Do the deed
collection.findOneAndReplace(filter, document, options);
} catch (Exception e) {
plugin.getLogger().severe(() -> "Could not save object " + instance.getClass().getName() + " " + e.getMessage());
plugin.logError("Could not save object " + instance.getClass().getName() + " " + e.getMessage());
}
}
@Override
public void deleteObject(T instance) {
if (!(instance instanceof DataObject)) {
plugin.getLogger().severe(() -> "This class is not a DataObject: " + instance.getClass().getName());
plugin.logError("This class is not a DataObject: " + instance.getClass().getName());
return;
}
try {
collection.findOneAndDelete(new Document(MONGO_ID, ((DataObject)instance).getUniqueId()));
} catch (Exception e) {
plugin.getLogger().severe(() -> "Could not delete object " + instance.getClass().getName() + " " + e.getMessage());
plugin.logError("Could not delete object " + instance.getClass().getName() + " " + e.getMessage());
}
}

View File

@ -70,7 +70,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try (PreparedStatement pstmt = connection.prepareStatement(sql.toString())) {
pstmt.executeUpdate();
} catch (SQLException e) {
plugin.getLogger().severe(() -> "Problem trying to create schema for data object " + dataObject.getCanonicalName() + " " + e.getMessage());
plugin.logError("Problem trying to create schema for data object " + dataObject.getCanonicalName() + " " + e.getMessage());
}
}
@ -107,7 +107,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
}
} catch (SQLException e) {
plugin.getLogger().severe(() -> "Could not load objects " + e.getMessage());
plugin.logError("Could not load objects " + e.getMessage());
}
return list;
}
@ -129,7 +129,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
}
} catch (SQLException e) {
plugin.getLogger().severe(() -> "Could not load object " + uniqueId + " " + e.getMessage());
plugin.logError("Could not load object " + uniqueId + " " + e.getMessage());
}
return null;
}
@ -137,7 +137,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@Override
public void saveObject(T instance) {
if (!(instance instanceof DataObject)) {
plugin.getLogger().severe(() -> "This class is not a DataObject: " + instance.getClass().getName());
plugin.logError("This class is not a DataObject: " + instance.getClass().getName());
return;
}
StringBuilder sb = new StringBuilder();
@ -154,14 +154,14 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
preparedStatement.setString(2, toStore);
preparedStatement.execute();
} catch (SQLException e) {
plugin.getLogger().severe(() -> "Could not save object " + instance.getClass().getName() + " " + e.getMessage());
plugin.logError("Could not save object " + instance.getClass().getName() + " " + e.getMessage());
}
}
@Override
public void deleteObject(T instance) {
if (!(instance instanceof DataObject)) {
plugin.getLogger().severe(() -> "This class is not a DataObject: " + instance.getClass().getName());
plugin.logError("This class is not a DataObject: " + instance.getClass().getName());
return;
}
StringBuilder sb = new StringBuilder();
@ -174,7 +174,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
preparedStatement.setString(1, uniqueId);
preparedStatement.execute();
} catch (Exception e) {
plugin.getLogger().severe(() -> "Could not delete object " + instance.getClass().getName() + " " + e.getMessage());
plugin.logError("Could not delete object " + instance.getClass().getName() + " " + e.getMessage());
}
}
@ -197,7 +197,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
}
} catch (SQLException e) {
plugin.getLogger().severe("Could not check if key exists in database! " + key + " " + e.getMessage());
plugin.logError("Could not check if key exists in database! " + key + " " + e.getMessage());
}
return false;
}
@ -208,7 +208,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try {
connection.close();
} catch (SQLException e) {
plugin.getLogger().severe("Could not close database for some reason");
plugin.logError("Could not close database for some reason");
}
}
}

View File

@ -31,7 +31,7 @@ public class IslandWorld {
return;
}
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName()) == null) {
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s Island World...");
plugin.log(CREATING + plugin.getName() + "'s Island World...");
}
// Create the world if it does not exist
islandWorld = WorldCreator.name(plugin.getSettings().getWorldName()).type(WorldType.FLAT).environment(World.Environment.NORMAL).generator(new ChunkGeneratorWorld(plugin))
@ -39,7 +39,7 @@ public class IslandWorld {
// Make the nether if it does not exist
if (plugin.getSettings().isNetherGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + NETHER) == null) {
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s Nether...");
plugin.log(CREATING + plugin.getName() + "'s Nether...");
}
if (!plugin.getSettings().isNetherIslands()) {
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + NETHER).type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
@ -51,7 +51,7 @@ public class IslandWorld {
// Make the end if it does not exist
if (plugin.getSettings().isEndGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + THE_END) == null) {
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s End World...");
plugin.log(CREATING + plugin.getName() + "'s End World...");
}
if (!plugin.getSettings().isEndIslands()) {
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + THE_END).type(WorldType.NORMAL).environment(World.Environment.THE_END).createWorld();
@ -66,28 +66,30 @@ public class IslandWorld {
private void fixMultiverse(BSkyBlock plugin) {
// Multiverse configuration
if (Bukkit.getServer().getPluginManager().isPluginEnabled("Multiverse-Core")) {
Bukkit.getLogger().info("Trying to register generator with Multiverse ");
plugin.log("Trying to register generator with Multiverse ");
try {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + " normal -g " + plugin.getName());
if (!Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName())) {
Bukkit.getLogger().severe("Multiverse is out of date! - Upgrade to latest version!");
}
Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + " normal -g " + plugin.getName()));
Bukkit.getScheduler().runTask(plugin, () -> {
if (!Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName())) {
plugin.logError("Multiverse is out of date! - Upgrade to latest version!");
}
});
if (netherWorld != null && plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_nether nether -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + NETHER);
Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_nether nether -g " + plugin.getName()));
Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + NETHER));
}
if (endWorld != null && plugin.getSettings().isEndGenerate() && plugin.getSettings().isEndIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_the_end end -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + THE_END);
Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_the_end end -g " + plugin.getName()));
Bukkit.getScheduler().runTask(plugin, () -> Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + THE_END));
}
} catch (Exception e) {
Bukkit.getLogger().severe("Not successfull! Disabling " + plugin.getName() + "!");
plugin.logError("Not successfull! Disabling " + plugin.getName() + "!");
Bukkit.getServer().getPluginManager().disablePlugin(plugin);
}
}

View File

@ -51,7 +51,7 @@ public class JoinLeaveListener implements Listener {
players.setPlayerName(user);
players.save(playerUUID);
} else {
plugin.getLogger().warning("Player that just logged in has no name! " + playerUUID.toString());
plugin.logWarning("Player that just logged in has no name! " + playerUUID.toString());
}
if (plugin.getSettings().isRemoveMobsOnLogin()) {
plugin.getIslands().removeMobs(user.getLocation());

View File

@ -6,7 +6,6 @@ package us.tastybento.bskyblock.listeners.flags;
import java.lang.reflect.Method;
import java.util.Optional;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
@ -177,7 +176,7 @@ public abstract class AbstractFlagListener implements Listener {
if (!createEventUser(e)) {
// The user is not set, and the event does not hold a getPlayer, so return false
// TODO: is this the correct handling here?
Bukkit.getLogger().severe("Check island had no associated user! " + e.getEventName());
plugin.logError("Check island had no associated user! " + e.getEventName());
return false;
}
}

View File

@ -56,7 +56,7 @@ public class AddonsManager {
try {
loadAddon(file);
} catch (InvalidAddonFormatException | InvalidAddonInheritException | InvalidDescriptionException e) {
plugin.getLogger().severe("Could not load addon " + file.getName() + " : " + e.getMessage());
plugin.logError("Could not load addon " + file.getName() + " : " + e.getMessage());
}
}
}
@ -65,7 +65,7 @@ public class AddonsManager {
try {
f.mkdir();
} catch (SecurityException e) {
Bukkit.getLogger().severe("Cannot create folder 'addons' (Permission ?)");
plugin.logError("Cannot create folder 'addons' (Permission ?)");
}
}
@ -73,7 +73,7 @@ public class AddonsManager {
addon.onEnable();
Bukkit.getPluginManager().callEvent(AddonEvent.builder().addon(addon).reason(AddonEvent.Reason.ENABLE).build());
addon.setEnabled(true);
plugin.getLogger().info("Enabling " + addon.getDescription().getName() + "...");
plugin.log("Enabling " + addon.getDescription().getName() + "...");
});
}
@ -144,12 +144,12 @@ public class AddonsManager {
addon.onLoad();
// Inform the console
plugin.getLogger().info("Loading BSkyBlock addon " + addon.getDescription().getName() + "...");
plugin.log("Loading BSkyBlock addon " + addon.getDescription().getName() + "...");
}
} catch (Exception e) {
if (DEBUG) {
plugin.getLogger().info(f.getName() + "is not a jarfile, ignoring...");
plugin.log(f.getName() + "is not a jarfile, ignoring...");
}
}
@ -163,7 +163,7 @@ public class AddonsManager {
addons.forEach(addon -> {
addon.onDisable();
Bukkit.getPluginManager().callEvent(AddonEvent.builder().addon(addon).reason(AddonEvent.Reason.DISABLE).build());
plugin.getLogger().info("Disabling " + addon.getDescription().getName() + "...");
plugin.log("Disabling " + addon.getDescription().getName() + "...");
});
loader.forEach(l -> {

View File

@ -274,7 +274,7 @@ public class IslandsManager {
if (island != null) {
deleteIsland(island, removeBlocks);
} else {
plugin.getLogger().severe(()->"Could not delete player: " + player.toString() + " island!");
plugin.logError("Could not delete player: " + player.toString() + " island!");
}
}
@ -445,7 +445,7 @@ public class IslandsManager {
}
}
if (l == null) {
plugin.getLogger().warning(()-> plugin.getPlayers().getName(playerUUID) + " player has no island!");
plugin.logWarning(plugin.getPlayers().getName(playerUUID) + " player has no island!");
return null;
}
// If these island locations are not safe, then we need to get creative
@ -636,7 +636,7 @@ public class IslandsManager {
islandCache.addIsland(island);
}
} catch (Exception e) {
plugin.getLogger().severe(()->"Could not load islands to cache! " + e.getMessage());
plugin.logError("Could not load islands to cache! " + e.getMessage());
}
}
@ -732,7 +732,7 @@ public class IslandsManager {
player.teleport(plugin.getIslandWorldManager().getIslandWorld().getSpawnLocation());
} else {
if (!player.performCommand(Constants.SPAWNCOMMAND)) {
plugin.getLogger().warning(()-> "During island deletion player " + player.getName() + " could not be sent to spawn so was dropped, sorry.");
plugin.logWarning("During island deletion player " + player.getName() + " could not be sent to spawn so was dropped, sorry.");
}
}
}
@ -752,7 +752,7 @@ public class IslandsManager {
try {
handler.saveObject(island);
} catch (Exception e) {
plugin.getLogger().severe(()->"Could not save island to datavase when running async! " + e.getMessage());
plugin.logError("Could not save island to datavase when running async! " + e.getMessage());
}
}
};
@ -762,7 +762,7 @@ public class IslandsManager {
try {
handler.saveObject(island);
} catch (Exception e) {
plugin.getLogger().severe(()->"Could not save island to datavase when running sync! " + e.getMessage());
plugin.logError("Could not save island to datavase when running sync! " + e.getMessage());
}
}
}

View File

@ -78,7 +78,7 @@ public class LocalesManager {
copyFile(name, targetFile);
}
} catch (IOException e) {
plugin.getLogger().severe("Could not copy locale files from jar " + e.getMessage());
plugin.logError("Could not copy locale files from jar " + e.getMessage());
}
}
@ -102,7 +102,7 @@ public class LocalesManager {
java.nio.file.Files.copy(initialStream, targetFile.toPath());
}
} catch (IOException e) {
plugin.getLogger().severe("Could not copy locale files from jar " + e.getMessage());
plugin.logError("Could not copy locale files from jar " + e.getMessage());
}
}

View File

@ -44,7 +44,7 @@ public class RanksManager {
public void loadCustomRanks() {
for (Entry<String, Integer> en : plugin.getSettings().getCustomRanks().entrySet()) {
if (!addRank(en.getKey(),en.getValue())) {
plugin.getLogger().severe("Error loading custom rank: " + en.getKey() + " " + en.getValue() + " skipping...");
plugin.logError("Error loading custom rank: " + en.getKey() + " " + en.getValue() + " skipping...");
}
}
}

View File

@ -70,23 +70,23 @@ public class IslandCache {
if (zEntry.containsKey(newIsland.getMinZ())) {
// Island already exists
Island conflict = islandGrid.get(newIsland.getMinX()).get(newIsland.getMinZ());
plugin.getLogger().warning("*** Duplicate or overlapping islands! ***");
plugin.getLogger().warning(
plugin.logWarning("*** Duplicate or overlapping islands! ***");
plugin.logWarning(
"Island at (" + newIsland.getCenter().getBlockX() + ", " + newIsland.getCenter().getBlockZ() + ") conflicts with ("
+ conflict.getCenter().getBlockX() + ", " + conflict.getCenter().getBlockZ() + ")");
if (conflict.getOwner() != null) {
plugin.getLogger().warning("Accepted island is owned by " + plugin.getPlayers().getName(conflict.getOwner()));
plugin.getLogger().warning(conflict.getOwner().toString() + ".yml");
plugin.logWarning("Accepted island is owned by " + plugin.getPlayers().getName(conflict.getOwner()));
plugin.logWarning(conflict.getOwner().toString() + ".yml");
} else {
plugin.getLogger().warning("Accepted island is unowned.");
plugin.logWarning("Accepted island is unowned.");
}
if (newIsland.getOwner() != null) {
plugin.getLogger().warning("Denied island is owned by " + plugin.getPlayers().getName(newIsland.getOwner()));
plugin.getLogger().warning(newIsland.getOwner().toString() + ".yml");
plugin.logWarning("Denied island is owned by " + plugin.getPlayers().getName(newIsland.getOwner()));
plugin.logWarning(newIsland.getOwner().toString() + ".yml");
} else {
plugin.getLogger().warning("Denied island is unowned and was just found in the islands folder. Skipping it...");
plugin.logWarning("Denied island is unowned and was just found in the islands folder. Skipping it...");
}
plugin.getLogger().warning("Recommend that the denied player file is deleted otherwise weird things can happen.");
plugin.logWarning("Recommend that the denied player file is deleted otherwise weird things can happen.");
return false;
} else {
// Add island

View File

@ -1,6 +1,5 @@
package us.tastybento.bskyblock.util;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@ -14,11 +13,9 @@ import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.user.User;
@ -221,46 +218,6 @@ public class Util {
return returned;
}
/**
* Loads a YAML file and if it does not exist it is looked for in the JAR
*
* @param file
* @return Yaml Config
*/
public static YamlConfiguration loadYamlFile(Plugin plugin, String file) {
File dataFolder = plugin.getDataFolder();
File yamlFile = new File(dataFolder, file);
YamlConfiguration config = null;
if (yamlFile.exists()) {
try {
config = new YamlConfiguration();
config.load(yamlFile);
} catch (Exception e) {
plugin.getLogger().severe("Could not load yml file " + e.getMessage());
}
} else {
// Create the missing file
config = new YamlConfiguration();
if (!file.startsWith("players")) {
plugin.getLogger().info("No " + file + " found. Creating it...");
}
try {
if (plugin.getResource(file) != null) {
plugin.getLogger().info("Using default found in jar file.");
plugin.saveResource(file, false);
config = new YamlConfiguration();
config.load(yamlFile);
} else {
config.save(yamlFile);
}
} catch (Exception e) {
plugin.getLogger().severe("Could not create the " + file + " file!");
}
}
return config;
}
/**
* Get the maximum value of a numerical perm setting
* @param player - the player - the player to check
@ -278,7 +235,7 @@ public class Util {
String[] spl = perms.getPermission().split(perm + ".");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
plugin.getLogger().severe("Player " + player.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
plugin.logError("Player " + player.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");
} else {
permValue = Math.max(permValue, Integer.valueOf(spl[1]));

View File

@ -88,11 +88,11 @@ public class SafeTeleportBuilder {
public SafeSpotTeleport build() {
// Error checking
if (entity == null) {
plugin.getLogger().severe("Attempt to safe teleport a null entity!");
plugin.logError("Attempt to safe teleport a null entity!");
return null;
}
if (location == null) {
plugin.getLogger().severe("Attempt to safe teleport to a null location!");
plugin.logError("Attempt to safe teleport to a null location!");
return null;
}
if (failureMessage.isEmpty() && entity instanceof Player) {

View File

@ -0,0 +1,109 @@
package us.tastybento.bskyblock.commands;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.plugin.PluginManager;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.Settings;
import us.tastybento.bskyblock.api.user.User;
import us.tastybento.bskyblock.managers.CommandsManager;
import us.tastybento.bskyblock.managers.IslandsManager;
import us.tastybento.bskyblock.managers.PlayersManager;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { BSkyBlock.class })
public class IslandCommandTest {
@Mock
static BSkyBlock plugin;
private static World world;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Server server = mock(Server.class);
world = mock(World.class);
when(server.getLogger()).thenReturn(Logger.getAnonymousLogger());
when(server.getWorld("world")).thenReturn(world);
when(server.getVersion()).thenReturn("BSB_Mocking");
PluginManager pluginManager = mock(PluginManager.class);
when(server.getPluginManager()).thenReturn(pluginManager);
Bukkit.setServer(server);
when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger());
plugin = mock(BSkyBlock.class);
Whitebox.setInternalState(BSkyBlock.class, "instance", plugin);
}
@Before
public void setUp() {
CommandsManager cm = new CommandsManager();
when(plugin.getCommandsManager()).thenReturn(cm);
}
@Test
public void testIslandCommand() {
assertNotNull(new IslandCommand());
}
@Test
public void testSetup() {
IslandCommand ic = new IslandCommand();
assertEquals("commands.island.help.description", ic.getDescription());
assertTrue(ic.isOnlyPlayer());
// Permission
assertEquals(Constants.PERMPREFIX + "island", ic.getPermission());
}
@Test
public void testExecuteUserListOfString() {
// Setup
IslandCommand ic = new IslandCommand();
assertFalse(ic.execute(null, null));
IslandsManager im = mock(IslandsManager.class);
when(plugin.getIslands()).thenReturn(im);
User user = mock(User.class);
UUID uuid = UUID.randomUUID();
when(user.getUniqueId()).thenReturn(uuid);
PlayersManager pm = mock(PlayersManager.class);
when(plugin.getPlayers()).thenReturn(pm);
Settings settings = mock(Settings.class);
when(plugin.getSettings()).thenReturn(settings);
// User has an island - so go there!
when(im.hasIsland(Mockito.eq(uuid))).thenReturn(true);
assertTrue(ic.execute(user, new ArrayList<>()));
// No island yet
when(im.hasIsland(Mockito.eq(uuid))).thenReturn(false);
assertTrue(ic.execute(user, new ArrayList<>()));
}
}