Merge pull request #125 from tastybento/config-api-v2

Submitting a modular and automatic Config API
This commit is contained in:
tastybento 2018-01-08 11:27:01 -08:00 committed by GitHub
commit 1b1e30c125
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
65 changed files with 2071 additions and 865 deletions

View File

@ -70,7 +70,7 @@ general:
mute-death-messages: false
# Allow FTB Autonomous Activator to work (will allow a pseudo player [CoFH] to place and break blocks and hang items)
FTB-auto-activator: false
allow-FTB-auto-activator: false
# Allow obsidian to be scooped up with an empty bucket back into lava
# This only works if there is a single block of obsidian (no obsidian within 10 blocks)
@ -102,7 +102,7 @@ world:
# Will be rounded up to the nearest 16 blocks.
# It is the same for every dimension : Overworld, Nether and End.
# This value cannot be changed mid-game and the plugin will not start if it is different.
distance: 64
distance-between-islands: 64
# Default protection range radius in blocks. Cannot be larger than distance.
# Admins can change protection sizes for players individually using /bsadmin setrange
@ -157,7 +157,11 @@ world:
# Minimum is 0 (not recommended), maximum is 100. Default is 25.
# Only applies to vanilla nether
spawn-radius: 25
end:
generate: true
islands: true
### Entities-related Settings ###
entities:
# Sets the limit for number of entities that can spawn in a chunk in this world.
@ -245,6 +249,25 @@ world:
### Island Settings ###
island:
# Default chest items
chest-items:
- ==: org.bukkit.inventory.ItemStack
type: LAVA_BUCKET
- ==: org.bukkit.inventory.ItemStack
type: ICE
amount: 2
- ==: org.bukkit.inventory.ItemStack
type: MELON_SEEDS
- ==: org.bukkit.inventory.ItemStack
type: BONE
amount: 2
- ==: org.bukkit.inventory.ItemStack
type: COBBLESTONE
amount: 5
- ==: org.bukkit.inventory.ItemStack
type: SAPLING
amount: 2
# Default max team size
# Use this permission to set for specific user groups: askyblock.team.maxsize.<number>
# Permission size cannot be less than the default below.
@ -404,7 +427,7 @@ protection:
# Restrict Wither and other flying mobs.
# Any flying mobs that exit the island space where they were spawned will be removed.
# Includes blaze and ghast.
restrict-wither: true
restrict-flying-mobs: true
# Invincible visitors - Prevent players from killing them (intentionally or by accident)
# If they fall to the void, they get TP'd to their island.

View File

@ -1,14 +1,10 @@
package us.tastybento.bskyblock;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import us.tastybento.bskyblock.commands.AdminCommand;
import us.tastybento.bskyblock.commands.IslandCommand;
import us.tastybento.bskyblock.config.PluginConfig;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.managers.PlayersManager;
import us.tastybento.bskyblock.database.managers.island.IslandsManager;
@ -41,74 +37,78 @@ public class BSkyBlock extends JavaPlugin {
private LocalesManager localesManager;
private AddonsManager addonsManager;
private FlagsManager flagsManager;
private IslandWorld islandWorldManager;
// Settings
Settings settings;
@Override
public void onEnable(){
// Save the default config from config.yml
saveDefaultConfig();
plugin = this;
// Load configuration and locales. If there are no errors, load the plugin.
if(PluginConfig.loadPluginConfig(this)){
playersManager = new PlayersManager(this);
islandsManager = new IslandsManager(this);
settings = new Settings();
// Load settings from config.yml. This will check if there are any issues with it too.
try {
//settings.saveSettings();
settings = settings.loadSettings();
} catch (Exception e) {
e.printStackTrace();
}
// Only load metrics if set to true in config
// Save a backup of settings to the database so it can be checked next time
try {
settings.saveBackup();
} catch (Exception e) {
e.printStackTrace();
}
if(Settings.metrics) {
metrics = new Metrics(plugin);
playersManager = new PlayersManager(this);
islandsManager = new IslandsManager(this);
registerCustomCharts();
// Load metrics
metrics = new Metrics(plugin);
registerCustomCharts();
}
// Set up commands
commandsManager = new CommandsManager();
new IslandCommand();
new AdminCommand();
// Set up commands
commandsManager = new CommandsManager();
new IslandCommand();
new AdminCommand();
// These items have to be loaded when the server has done 1 tick.
// Note Worlds are not loaded this early, so any Locations or World reference will be null
// at this point. Therefore, the 1 tick scheduler is required.
getServer().getScheduler().runTask(this, new Runnable() {
// These items have to be loaded when the server has done 1 tick.
// Note Worlds are not loaded this early, so any Locations or World reference will be null
// at this point. Therefore, the 1 tick scheduler is required.
getServer().getScheduler().runTask(this, new Runnable() {
@Override
public void run() {
// Create the world if it does not exist
islandWorldManager = new IslandWorld(plugin);
@Override
public void run() {
// Create the world if it does not exist
new IslandWorld(plugin);
getServer().getScheduler().runTask(plugin, new Runnable() {
getServer().getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
// Load islands from database
islandsManager.load();
@Override
public void run() {
// Load islands from database
islandsManager.load();
// TODO: load these from config.yml
Settings.chestItems = new ItemStack[] {
new ItemStack(Material.LAVA_BUCKET,1),
new ItemStack(Material.ICE,2),
new ItemStack(Material.MELON_SEEDS,1),
new ItemStack(Material.BONE,2),
new ItemStack(Material.COBBLESTONE,5),
new ItemStack(Material.SAPLING,2)
};
localesManager = new LocalesManager(plugin);
//TODO localesManager.registerLocales(plugin);
Settings.defaultLanguage = "en-US";
localesManager = new LocalesManager(plugin);
//TODO localesManager.registerLocales(plugin);
// Register Listeners
registerListeners();
// Register Listeners
registerListeners();
// Load Flags
flagsManager = new FlagsManager();
// Load Flags
flagsManager = new FlagsManager();
// Load addons
addonsManager = new AddonsManager(plugin);
addonsManager.enableAddons();
// Load addons
addonsManager = new AddonsManager(plugin);
addonsManager.enableAddons();
/*
*DEBUG CODE
/*
*DEBUG CODE
Island loadedIsland = islandsManager.getIsland(owner);
getLogger().info("Island name = " + loadedIsland.getName());
getLogger().info("Island locked = " + loadedIsland.getLocked());
@ -117,24 +117,25 @@ public class BSkyBlock extends JavaPlugin {
for (Entry<SettingsFlag, Boolean> flag: loadedIsland.getFlags().entrySet()) {
getLogger().info("Flag " + flag.getKey().name() + " = " + flag.getValue());
}
*/
// Save islands & players data asynchronously every X minutes
Settings.databaseBackupPeriod = 10 * 60 * 20;
plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
*/
// Save islands & players data asynchronously every X minutes
getSettings().setDatabaseBackupPeriod(10 * 60 * 20);
plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
playersManager.save(true);
islandsManager.save(true);
}
}, Settings.databaseBackupPeriod, Settings.databaseBackupPeriod);
}
});
}
});
}
@Override
public void run() {
playersManager.save(true);
islandsManager.save(true);
}
}, getSettings().getDatabaseBackupPeriod(), getSettings().getDatabaseBackupPeriod());
}
});
}
});
}
private void registerListeners() {
PluginManager manager = getServer().getPluginManager();
// Player join events
@ -173,7 +174,7 @@ public class BSkyBlock extends JavaPlugin {
@Override
public String getValue() {
return Settings.defaultLanguage;
return getSettings().getDefaultLanguage();
}
});
@ -234,4 +235,19 @@ public class BSkyBlock extends JavaPlugin {
return flagsManager;
}
/**
* @return the settings
*/
public Settings getSettings() {
return settings;
}
/**
* @return the Island World Manager
*/
public IslandWorld getIslandWorldManager() {
return islandWorldManager;
}
}

View File

@ -0,0 +1,39 @@
package us.tastybento.bskyblock;
/**
* All the plugin settings are here
* @author Tastybento
*/
public class Constants {
// ----------------- Constants -----------------
// Game Type BSKYBLOCK or ACIDISLAND
public enum GameType {
BSKYBLOCK, ACIDISLAND, BOTH
}
/*
public final static GameType GAMETYPE = GameType.ACIDISLAND;
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
// Permission prefix
public final static String PERMPREFIX = "acidisland.";
// The island command
public final static String ISLANDCOMMAND = "ai";
// The challenge command
public static final String CHALLENGECOMMAND = "aic";
// Admin command
public static final String ADMINCOMMAND = "acid";
*/
public final static GameType GAMETYPE = GameType.BSKYBLOCK;
// Permission prefix
public final static String PERMPREFIX = "bskyblock.";
// The island command
public final static String ISLANDCOMMAND = "island";
// The challenge command
public static final String CHALLENGECOMMAND = "bsc";
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
// Admin command
public static final String ADMINCOMMAND = "bsadmin";
}

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,13 @@
package us.tastybento.bskyblock.api.addons;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
@ -25,6 +24,7 @@ import us.tastybento.bskyblock.BSkyBlock;
public abstract class Addon implements AddonInterface {
private static final String ADDON_CONFIG_FILENAME = "config.yml";
private static final boolean DEBUG = false;
private boolean enabled;
private AddonDescription description;
private FileConfiguration config;
@ -146,53 +146,44 @@ public abstract class Addon implements AddonInterface {
/**
* Saves a resource contained in this add-on's jar file to the destination folder.
* @param resourcePath in jar file
* @param jarResource in jar file
* @param destinationFolder on file system
* @param replace - if true, will overwrite previous file
* @param prefix - if true, filename will be prefixed with the name of this addon
* @param noPath - if true, the resource's path will be ignored when saving
*/
public void saveResource(String resourcePath, File destinationFolder, boolean replace, boolean prefix) {
if (resourcePath == null || resourcePath.equals("")) {
public void saveResource(String jarResource, File destinationFolder, boolean replace, boolean noPath) {
if (jarResource == null || jarResource.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
jarResource = jarResource.replace('\\', '/');
InputStream in = null;
try {
JarFile jar = new JarFile(file);
JarEntry config = jar.getJarEntry(resourcePath);
JarEntry config = jar.getJarEntry(jarResource);
if (config != null) {
in = jar.getInputStream(config);
}
if (in == null) {
jar.close();
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + jar.getName());
throw new IllegalArgumentException("The embedded resource '" + jarResource + "' cannot be found in " + jar.getName());
}
File outFile = new File(destinationFolder, resourcePath);
//Bukkit.getLogger().info("DEBUG: outFile = " + outFile.getAbsolutePath());
//Bukkit.getLogger().info("DEBUG: outFile name = " + outFile.getName());
if (prefix) {
// Rename with addon prefix
outFile = new File(outFile.getParent(), getDescription().getName() + "-" + outFile.getName());
// There are two options, use the path of the resource or not
File outFile = new File(destinationFolder, jarResource);
if (noPath) {
outFile = new File(destinationFolder, outFile.getName());
}
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(destinationFolder, resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
//Bukkit.getLogger().info("DEBUG: outDir = " + outDir.getAbsolutePath());
if (!outDir.exists()) {
outDir.mkdirs();
// Make any dirs that need to be made
outFile.getParentFile().mkdirs();
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: outFile = " + outFile.getAbsolutePath());
Bukkit.getLogger().info("DEBUG: outFile name = " + outFile.getName());
}
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
java.nio.file.Files.copy(in, outFile.toPath());
}
in.close();
jar.close();
} catch (IOException ex) {
ex.printStackTrace();

View File

@ -17,6 +17,7 @@ import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Settings;
import us.tastybento.bskyblock.api.events.command.CommandEvent;
import us.tastybento.bskyblock.database.managers.PlayersManager;
import us.tastybento.bskyblock.database.managers.island.IslandsManager;
@ -59,6 +60,23 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/
private String usage;
/**
* Used only for testing....
*/
public CompositeCommand(BSkyBlock plugin, String label, String... string) {
super(label);
this.setAliases(new ArrayList<>(Arrays.asList(string)));
this.parent = null;
setUsage("");
this.subCommandLevel = 0; // Top level
this.subCommands = new LinkedHashMap<>();
this.setup();
if (!this.getSubCommand("help").isPresent() && !label.equals("help"))
new DefaultHelpCommand(this);
}
/**
* Sub-command constructor
* @param parent - the parent composite command
@ -83,7 +101,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
Bukkit.getLogger().info("DEBUG: registering command " + label);
}
/**
* This is the top-level command constructor for commands that have no parent.
* @param label - string for this command
@ -108,22 +125,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
}
/**
* Used only for testing....
*/
public CompositeCommand(BSkyBlock plugin, String label, String... string) {
super(label);
this.setAliases(new ArrayList<>(Arrays.asList(string)));
this.parent = null;
setUsage("");
this.subCommandLevel = 0; // Top level
this.subCommands = new LinkedHashMap<>();
this.setup();
if (!this.getSubCommand("help").isPresent() && !label.equals("help"))
new DefaultHelpCommand(this);
}
/*
* This method deals with the command execution. It traverses the tree of
@ -227,6 +228,10 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return getPlugin().getIslands().getMembers(user.getUniqueId());
}
public String getParameters() {
return parameters;
}
/**
* @return the parent command object
*/
@ -246,12 +251,20 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
protected PlayersManager getPlayers() {
return getPlugin().getPlayers();
}
@Override
public BSkyBlock getPlugin() {
return BSkyBlock.getInstance();
}
/**
* @return Settings object
*/
public Settings getSettings() {
return getPlugin().getSettings();
}
/**
* Returns the CompositeCommand object refering to this command label
* @param label - command label or alias
@ -264,6 +277,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
}
return Optional.empty();
}
/**
* @return Map of sub commands for this command
@ -272,7 +286,6 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return subCommands;
}
/**
* Convenience method to obtain the user's team leader
* @param user
@ -282,41 +295,11 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return getPlugin().getIslands().getTeamLeader(user.getUniqueId());
}
public void setparameters(String parameters) {
this.setParameters(parameters);
}
@Override
public String getUsage() {
return "/" + usage;
}
/**
* This creates the full linking chain of commands
*/
@Override
public Command setUsage(String usage) {
// Go up the chain
CompositeCommand parent = this.getParent();
this.usage = this.getLabel() + " " + usage;
while (parent != null) {
this.usage = parent.getLabel() + " " + this.usage;
parent = parent.getParent();
}
this.usage = this.usage.trim();
return this;
}
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
/**
* Check if this command has a specific sub command
* @param subCommand
@ -326,6 +309,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return subCommands.containsKey(subCommand);
}
/**
* Check if this command has any sub commands
* @return true if this command has subcommands
@ -368,11 +352,31 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
this.onlyPlayer = onlyPlayer;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
@Override
public void setPermission(String permission) {
this.permission = permission;
}
/**
* This creates the full linking chain of commands
*/
@Override
public Command setUsage(String usage) {
// Go up the chain
CompositeCommand parent = this.getParent();
this.usage = this.getLabel() + " " + usage;
while (parent != null) {
this.usage = parent.getLabel() + " " + this.usage;
parent = parent.getParent();
}
this.usage = this.usage.trim();
return this;
}
@Override
public List<String> tabComplete(final CommandSender sender, final String alias, final String[] args) {
List<String> options = new ArrayList<>();

View File

@ -17,7 +17,6 @@ import org.bukkit.inventory.PlayerInventory;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
/**
* BSB's user object. Wraps Player.
@ -255,7 +254,7 @@ public class User {
if (!plugin.getPlayers().getLocale(this.playerUUID).isEmpty())
return Locale.forLanguageTag(plugin.getPlayers().getLocale(this.playerUUID));
}
return Locale.forLanguageTag(Settings.defaultLanguage);
return Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage());
}
}

View File

@ -0,0 +1,13 @@
package us.tastybento.bskyblock.api.configuration;
public interface Adapter<S,V> {
/**
* Convert from to something
* @param from
*/
S convertFrom(Object from);
V convertTo(Object to);
}

View File

@ -0,0 +1,27 @@
package us.tastybento.bskyblock.api.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import us.tastybento.bskyblock.Constants.GameType;
/**
*
*
* @author Poslovitch, tastybento
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ConfigEntry {
String path();
String since() default "1.0";
boolean overrideOnChange() default false;
boolean experimental() default false;
boolean needsReset() default false;
GameType specificTo() default GameType.BOTH;
Class<?> adapter() default Adapter.class;
}

View File

@ -0,0 +1,5 @@
package us.tastybento.bskyblock.api.configuration;
public abstract class Conversion {
public abstract void convert();
}

View File

@ -0,0 +1,70 @@
package us.tastybento.bskyblock.api.configuration;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import org.bukkit.Bukkit;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.flatfile.FlatFileDatabase;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
/**
* Simple interface for tagging all classes containing ConfigEntries.
*
* @author Poslovitch
* @param <T>
*/
public interface ISettings<T> {
// ----------------Saver-------------------
@SuppressWarnings("unchecked")
default void saveSettings() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
// Get the handler
AbstractDatabaseHandler<T> settingsHandler = (AbstractDatabaseHandler<T>) new FlatFileDatabase().getHandler(getInstance().getClass());
// Load every field in the config class
Bukkit.getLogger().info("DEBUG: settingsHandler = " + settingsHandler);
Bukkit.getLogger().info("DEBUG: instance = " + getInstance());
settingsHandler.saveSettings(getInstance());
}
default void saveBackup() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
// Save backup in real database
@SuppressWarnings("unchecked")
AbstractDatabaseHandler<T> dbhandler = (AbstractDatabaseHandler<T>) BSBDatabase.getDatabase().getHandler(getInstance().getClass());
dbhandler.saveObject(getInstance());
}
// --------------- Loader ------------------
@SuppressWarnings("unchecked")
default T loadSettings() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, ClassNotFoundException, IntrospectionException, SQLException {
// See if this settings object already exists in the database
AbstractDatabaseHandler<T> dbhandler = (AbstractDatabaseHandler<T>) BSBDatabase.getDatabase().getHandler(this.getClass());
T dbConfig = null;
if (dbhandler.objectExits(this.getUniqueId())) {
// Load it
dbConfig = dbhandler.loadObject(getUniqueId());
}
// Get the handler
AbstractDatabaseHandler<T> configHandler = (AbstractDatabaseHandler<T>) new FlatFileDatabase().getHandler(getInstance().getClass());
// Load every field in the config class
return configHandler.loadSettings(getUniqueId(), dbConfig);
}
/**
* @return instance of the implementing class, i.e., return this.
*/
T getInstance();
/**
* @return the uniqueId
*/
String getUniqueId();
/**
* @param uniqueId the uniqueId to set
*/
void setUniqueId(String uniqueId);
}

View File

@ -0,0 +1,34 @@
package us.tastybento.bskyblock.api.configuration;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.potion.PotionEffectType;
public class PotionEffectListAdpater implements Adapter<List<PotionEffectType>, List<String>> {
@SuppressWarnings("unchecked")
@Override
public List<PotionEffectType> convertFrom(Object from) {
List<PotionEffectType> result = new ArrayList<>();
if (from instanceof ArrayList) {
for (String type: (ArrayList<String>)from) {
result.add(PotionEffectType.getByName(type));
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<String> convertTo(Object to) {
List<String> result = new ArrayList<>();
if (to instanceof ArrayList) {
for (PotionEffectType type: (ArrayList<PotionEffectType>)to) {
result.add(type.getName());
}
}
return result;
}
}

View File

@ -0,0 +1,27 @@
package us.tastybento.bskyblock.api.configuration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Defines where this data object will be stored.
* @author tastybento
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface StoreAt {
/**
* Path where this will be stored. If blank, it will be the BSkyBlock database folder.
*/
String path() default "";
/**
* Filename
*/
String filename() default "";
}

View File

@ -3,6 +3,7 @@ package us.tastybento.bskyblock.api.events.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Cancellable;
import us.tastybento.bskyblock.api.events.PremadeEvent;
/**

View File

@ -4,6 +4,7 @@ import java.util.List;
import java.util.UUID;
import org.bukkit.event.Cancellable;
import us.tastybento.bskyblock.api.events.PremadeEvent;
/**

View File

@ -1,10 +1,11 @@
package us.tastybento.bskyblock.api.flags;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.api.panels.PanelItem;
import java.util.Optional;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.api.panels.PanelItem;
public class Flag {
private String id;

View File

@ -1,10 +1,11 @@
package us.tastybento.bskyblock.api.flags;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.api.panels.PanelItem;
import java.util.Optional;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.api.panels.PanelItem;
public class FlagBuilder {
private String id;

View File

@ -1,11 +1,8 @@
package us.tastybento.bskyblock.api.localization;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
/**

View File

@ -2,23 +2,25 @@ package us.tastybento.bskyblock.commands;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.commands.admin.AdminReloadCommand;
import us.tastybento.bskyblock.commands.admin.AdminVersionCommand;
import us.tastybento.bskyblock.config.Settings;
public class AdminCommand extends CompositeCommand {
public AdminCommand() {
super(Settings.ADMINCOMMAND, "bsb");
super(Constants.ADMINCOMMAND, "bsb");
}
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "admin.*");
this.setPermission(Constants.PERMPREFIX + "admin.*");
this.setOnlyPlayer(false);
this.setDescription("admin.help.description");
new AdminVersionCommand(this);
new AdminReloadCommand(this);
}
@Override

View File

@ -2,6 +2,7 @@ package us.tastybento.bskyblock.commands;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.commands.island.IslandAboutCommand;
@ -12,12 +13,11 @@ import us.tastybento.bskyblock.commands.island.IslandResetnameCommand;
import us.tastybento.bskyblock.commands.island.IslandSethomeCommand;
import us.tastybento.bskyblock.commands.island.IslandSetnameCommand;
import us.tastybento.bskyblock.commands.island.teams.IslandTeamCommand;
import us.tastybento.bskyblock.config.Settings;
public class IslandCommand extends CompositeCommand {
public IslandCommand() {
super(Settings.ISLANDCOMMAND, "is");
super(Constants.ISLANDCOMMAND, "is");
}
/* (non-Javadoc)
@ -28,7 +28,7 @@ public class IslandCommand extends CompositeCommand {
this.setDescription("commands.island.help.description");
this.setOnlyPlayer(true);
// Permission
this.setPermission(Settings.PERMPREFIX + "island");
this.setPermission(Constants.PERMPREFIX + "island");
// Set up subcommands
new IslandAboutCommand(this);
new IslandCreateCommand(this);

View File

@ -0,0 +1,43 @@
/**
*
*/
package us.tastybento.bskyblock.commands.admin;
import java.util.List;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
/**
* @author ben
*
*/
public class AdminReloadCommand extends CompositeCommand {
/**
* @param parent
* @param label
* @param aliases
*/
public AdminReloadCommand(CompositeCommand parent) {
super(parent, "reload");
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#setup()
*/
@Override
public void setup() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.api.commands.BSBCommand#execute(us.tastybento.bskyblock.api.commands.User, java.util.List)
*/
@Override
public boolean execute(User user, List<String> args) {
return true;
}
}

View File

@ -2,9 +2,9 @@ package us.tastybento.bskyblock.commands.admin;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
public class AdminVersionCommand extends CompositeCommand {
@ -15,7 +15,7 @@ public class AdminVersionCommand extends CompositeCommand {
@Override
public void setup() {
// Permission
this.setPermission(Settings.PERMPREFIX + "admin.version");
this.setPermission(Constants.PERMPREFIX + "admin.version");
}
@Override

View File

@ -2,9 +2,9 @@ package us.tastybento.bskyblock.commands.island;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
/**
@ -40,7 +40,7 @@ public class CustomIslandMultiHomeHelp extends CompositeCommand {
String desc = getDescription().isEmpty() ? "" : user.getTranslation(getDescription());
// Player. Check perms
if (user.hasPermission(getPermission())) {
int maxHomes = Util.getPermValue(user.getPlayer(), Settings.PERMPREFIX + "island.maxhomes", Settings.maxHomes);
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (maxHomes > 1) {
params = getParameters().isEmpty() ? "" : user.getTranslation(getParameters());
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);

View File

@ -6,11 +6,11 @@ package us.tastybento.bskyblock.commands.island;
import java.io.IOException;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.commands.IslandCommand;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.managers.island.NewIsland;
/**
@ -26,7 +26,7 @@ public class IslandCreateCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.create");
this.setPermission(Constants.PERMPREFIX + "island.create");
this.setOnlyPlayer(true);
this.setDescription("commands.island.create.description");
}
@ -55,7 +55,7 @@ public class IslandCreateCommand extends CompositeCommand {
*/
protected void createIsland(User user) {
try {
NewIsland.builder()
NewIsland.builder(getPlugin())
.player(user.getPlayer())
.reason(Reason.CREATE)
.build();

View File

@ -8,10 +8,10 @@ import java.util.List;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.ChatColor;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.commands.IslandCommand;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
/**
@ -26,7 +26,7 @@ public class IslandGoCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.home");
this.setPermission(Constants.PERMPREFIX + "island.home");
this.setOnlyPlayer(true);
this.setDescription("commands.island.go.description");
new CustomIslandMultiHomeHelp(this);
@ -43,7 +43,7 @@ public class IslandGoCommand extends CompositeCommand {
}
if (!args.isEmpty() && NumberUtils.isDigits(args.get(0))) {
int homeValue = Integer.valueOf(args.get(0));
int maxHomes = Util.getPermValue(user.getPlayer(), Settings.PERMPREFIX + "island.maxhomes", Settings.maxHomes);
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (homeValue > 1 && homeValue <= maxHomes) {
getIslands().homeTeleport(user.getPlayer(), homeValue);
return true;

View File

@ -6,10 +6,10 @@ import java.util.List;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.managers.island.NewIsland;
import us.tastybento.bskyblock.database.objects.Island;
@ -23,7 +23,7 @@ public class IslandResetCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.create");
this.setPermission(Constants.PERMPREFIX + "island.create");
this.setOnlyPlayer(true);
this.setDescription("commands.island.reset.description");
}
@ -56,7 +56,7 @@ public class IslandResetCommand extends CompositeCommand {
if (DEBUG)
getPlugin().getLogger().info("DEBUG: making new island ");
try {
NewIsland.builder()
NewIsland.builder(getPlugin())
.player(player)
.reason(Reason.RESET)
.oldIsland(oldIsland)

View File

@ -6,9 +6,9 @@ package us.tastybento.bskyblock.commands.island;
import java.util.List;
import java.util.UUID;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
/**
* @author tastybento
@ -22,7 +22,7 @@ public class IslandResetnameCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.name");
this.setPermission(Constants.PERMPREFIX + "island.name");
this.setOnlyPlayer(true);
this.setDescription("commands.island.resetname.description");

View File

@ -3,9 +3,9 @@ package us.tastybento.bskyblock.commands.island;
import java.util.List;
import java.util.UUID;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
public class IslandSethomeCommand extends CompositeCommand {
@ -16,7 +16,7 @@ public class IslandSethomeCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.sethome");
this.setPermission(Constants.PERMPREFIX + "island.sethome");
this.setOnlyPlayer(true);
this.setDescription("commands.island.sethome.description");
new CustomIslandMultiHomeHelp(this);
@ -40,7 +40,7 @@ public class IslandSethomeCommand extends CompositeCommand {
user.sendMessage("commands.island.sethome.home-set");
} else {
// Dynamic home sizes with permissions
int maxHomes = Util.getPermValue(user.getPlayer(), Settings.PERMPREFIX + "island.maxhomes", Settings.maxHomes);
int maxHomes = Util.getPermValue(user.getPlayer(), Constants.PERMPREFIX + "island.maxhomes", getSettings().getMaxHomes());
if (maxHomes > 1) {
// Check the number given is a number
int number = 0;

View File

@ -10,9 +10,9 @@ import java.util.stream.Collectors;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
/**
* @author tastybento
@ -26,7 +26,7 @@ public class IslandSetnameCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.name");
this.setPermission(Constants.PERMPREFIX + "island.name");
this.setOnlyPlayer(true);
this.setParameters("commands.island.setname.parameters");
this.setDescription("commands.island.setname.description");
@ -59,17 +59,17 @@ public class IslandSetnameCommand extends CompositeCommand {
String name = args.stream().collect(Collectors.joining( " " ));
// Check if the name isn't too short or too long
if (name.length() < Settings.nameMinLength) {
user.sendMessage("commands.island.setname.too-short", "[length]", String.valueOf(Settings.nameMinLength));
if (name.length() < getSettings().getNameMinLength()) {
user.sendMessage("commands.island.setname.too-short", "[length]", String.valueOf(getSettings().getNameMinLength()));
return true;
}
if (name.length() > Settings.nameMaxLength) {
user.sendMessage("commands.island.setname.too-long", "[length]", String.valueOf(Settings.nameMaxLength));
if (name.length() > getSettings().getNameMaxLength()) {
user.sendMessage("commands.island.setname.too-long", "[length]", String.valueOf(getSettings().getNameMaxLength()));
return true;
}
// Set the name
if (!player.hasPermission(Settings.PERMPREFIX + "island.name.format"))
if (!player.hasPermission(Constants.PERMPREFIX + "island.name.format"))
getIslands().getIsland(player.getUniqueId()).setName(ChatColor.translateAlternateColorCodes('&', name));
else getIslands().getIsland(playerUUID).setName(name);

View File

@ -13,7 +13,6 @@ import com.google.common.collect.HashBiMap;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
/**
* A safe common space for team commands to share data
@ -42,6 +41,6 @@ public abstract class AbstractIslandTeamCommand extends CompositeCommand {
* @param player
*/
protected void setResetWaitTime(final Player player) {
resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + Settings.resetWait * 1000);
resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + getSettings().getResetWait() * 1000);
}
}

View File

@ -7,11 +7,11 @@ import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
public class IslandTeamCommand extends AbstractIslandTeamCommand {
@ -23,7 +23,7 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.description");
@ -50,15 +50,15 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
UUID teamLeaderUUID = getTeamLeader(user);
Set<UUID> teamMembers = getMembers(user);
if (teamLeaderUUID.equals(playerUUID)) {
int maxSize = Settings.maxTeamSize;
int maxSize = getSettings().getMaxTeamSize();
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Settings.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Settings.PERMPREFIX + "team.maxsize.*")) {
maxSize = Settings.maxTeamSize;
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Settings.PERMPREFIX + "team.maxsize.");
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");

View File

@ -7,10 +7,10 @@ import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
@ -21,7 +21,7 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.accept.description");
}
@ -88,13 +88,13 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
// Set the cooldown
setResetWaitTime(user.getPlayer());
// Reset deaths
if (Settings.teamJoinDeathReset) {
if (getSettings().isTeamJoinDeathReset()) {
getPlayers().setDeaths(playerUUID, 0);
}
// Put player back into normal mode
user.setGameMode(GameMode.SURVIVAL);
user.sendMessage("commands.island.team.invite.accept.you-joined-island", "[label]", Settings.ISLANDCOMMAND);
user.sendMessage("commands.island.team.invite.accept.you-joined-island", "[label]", Constants.ISLANDCOMMAND);
User inviter = User.getInstance(inviteList.get(playerUUID));
if (inviter != null) {
inviter.sendMessage("commands.island.team.invite.accept.name-joined-your-island", "[name]", user.getName());

View File

@ -11,10 +11,10 @@ import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.OfflinePlayer;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
@ -25,7 +25,7 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.description");
@ -84,16 +84,16 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
}
Set<UUID> teamMembers = getMembers(user);
// Check if player has space on their team
int maxSize = Settings.maxTeamSize;
int maxSize = getSettings().getMaxTeamSize();
// Dynamic team sizes with permissions
for (PermissionAttachmentInfo perms : user.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Settings.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Settings.PERMPREFIX + "team.maxsize.*")) {
maxSize = Settings.maxTeamSize;
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "team.maxsize.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "team.maxsize.*")) {
maxSize = getSettings().getMaxTeamSize();
break;
} else {
// Get the max value should there be more than one
String[] spl = perms.getPermission().split(Settings.PERMPREFIX + "team.maxsize.");
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "team.maxsize.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");

View File

@ -3,10 +3,10 @@ package us.tastybento.bskyblock.commands.island.teams;
import java.util.List;
import java.util.UUID;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
@ -16,7 +16,7 @@ public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.reject.description");
}

View File

@ -2,8 +2,8 @@ package us.tastybento.bskyblock.commands.island.teams;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
@ -13,7 +13,7 @@ public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.leave.description");

View File

@ -2,8 +2,8 @@ package us.tastybento.bskyblock.commands.island.teams;
import java.util.List;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
public class IslandTeamPromoteCommand extends AbstractIslandTeamCommand {
@ -13,7 +13,7 @@ public class IslandTeamPromoteCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setParameters("commands.island.team.promote.parameters");
this.setDescription("commands.island.team.promote.description");

View File

@ -9,10 +9,10 @@ import java.util.UUID;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.util.Util;
@ -24,7 +24,7 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Settings.PERMPREFIX + "island.team");
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setParameters("commands.island.team.setowner.parameters");
this.setDescription("commands.island.team.setowner.description");
@ -81,7 +81,7 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
if (target.isOnline()) {
// Check if new leader has a lower range permission than the island size
boolean hasARangePerm = false;
int range = Settings.islandProtectionRange;
int range = getSettings().getIslandProtectionRange();
// Check for zero protection range
Island islandByOwner = getIslands().getIsland(targetUUID);
if (islandByOwner.getProtectionRange() == 0) {
@ -89,12 +89,12 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
islandByOwner.setProtectionRange(range);
}
for (PermissionAttachmentInfo perms : target.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Settings.PERMPREFIX + "island.range.")) {
if (perms.getPermission().contains(Settings.PERMPREFIX + "island.range.*")) {
if (perms.getPermission().startsWith(Constants.PERMPREFIX + "island.range.")) {
if (perms.getPermission().contains(Constants.PERMPREFIX + "island.range.*")) {
// Ignore
break;
} else {
String[] spl = perms.getPermission().split(Settings.PERMPREFIX + "island.range.");
String[] spl = perms.getPermission().split(Constants.PERMPREFIX + "island.range.");
if (spl.length > 1) {
if (!NumberUtils.isDigits(spl[1])) {
getPlugin().getLogger().severe("Player " + user.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring...");

View File

@ -1,76 +0,0 @@
package us.tastybento.bskyblock.config;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import us.tastybento.bskyblock.BSkyBlock;
/**
* This class runs when the config file is not set up enough, or is unsafe.
* It provides useful information to the admin on what is wrong.
*
* @author Tastybento
* @author Poslovitch
*/
public class NotSetup implements CommandExecutor{
public enum ConfigError {
DIFFERENT_WORLDNAME(0, 001),
DIFFERENT_ISLAND_DISTANCE(0, 002),
PROTECTION_RANGE_HIGHER_THAN_ISLAND_DISTANCE(1, 101),
UNKNOWN_LANGUAGE(2, 201),
NOT_CHUNK_ISLAND_DISTANCE(2, 202),
NOT_EVEN_PROTECTION_RANGE(2, 203),
PURGE_ISLAND_LEVEL_TOO_LOW(3, 301),
ISLAND_DISTANCE_TOO_LOW(3, 302),
PROTECTION_RANGE_TOO_LOW(3, 303),
ISLAND_HEIGHT_TOO_LOW(3, 304),
NETHER_SPAWN_RADIUS_TOO_LOW(3, 305),
NETHER_SPAWN_RADIUS_TOO_HIGH(3, 306);
/*
* Priority:
* 0 - CRITICAL
* 1 - HIGH
* 2 - MEDIUM
* 3 - LOW
*/
private int priority;
private int id;
ConfigError(int priority, int id){
this.priority = priority;
this.id = id;
}
public static ConfigError getById(int id){
for(ConfigError e : ConfigError.values()){
if(e.id == id) return e;
}
return null;
}
}
private BSkyBlock plugin;
private List<Error> errors;
/**
* Handles plugin operation if a critical config-related issue happened
*
* @param plugin
* @param errors
*/
public NotSetup(BSkyBlock plugin, List<Error> errors){
this.plugin = plugin;
this.errors = errors;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return true;
}
}

View File

@ -1,134 +0,0 @@
package us.tastybento.bskyblock.config;
import java.util.HashMap;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.NotSetup.ConfigError;
import us.tastybento.bskyblock.database.BSBDatabase.DatabaseType;
/**
* Loads the plugin configuration and the locales.
* Also provides
*
* @author Tastybento
* @author Poslovitch
*/
public class PluginConfig {
/**
* Loads the plugin configuration and the locales.
* If there were errors, it setups the commands as "NotSetup" and generates a debug for admins to fix their configuration.
* @return true if there wasn't any error, otherwise false.
*/
public static boolean loadPluginConfig(BSkyBlock plugin) {
plugin.saveDefaultConfig();
// Initialize the errors list
HashMap<ConfigError, Object> errors = new HashMap<>();
//TODO config version
// The order in this file should match the order in config.yml so that it's easy to check that everything is covered
// ********************* General *********************
Settings.metrics = plugin.getConfig().getBoolean("general.metrics", true);
Settings.checkUpdates = plugin.getConfig().getBoolean("general.check-updates", true);
//loadLocales(plugin);
Settings.defaultLanguage = plugin.getConfig().getString("general.default-language", "en-US");
//if(!plugin.getLocales().containsKey(Settings.defaultLanguage)) errors.put(ConfigError.UNKNOWN_LANGUAGE, Settings.defaultLanguage);
Settings.useEconomy = plugin.getConfig().getBoolean("general.use-economy", true);
Settings.startingMoney = plugin.getConfig().getDouble("general.starting-money", 10.0);
//Settings.useControlPanel = plugin.getConfig().getBoolean("general.use-control-panel", true);
// Purge
Settings.purgeMaxIslandLevel = plugin.getConfig().getInt("general.purge.max-island-level", 50);
if(Settings.purgeMaxIslandLevel < 0) errors.put(ConfigError.PURGE_ISLAND_LEVEL_TOO_LOW, Settings.purgeMaxIslandLevel);
Settings.purgeRemoveUserData = plugin.getConfig().getBoolean("general.purge.remove-user-data", false);
// Database
String dbType = plugin.getConfig().getString("general.database.type","FLATFILE");
boolean found = false;
for (DatabaseType type: DatabaseType.values()) {
if (type.name().equals(dbType.toUpperCase())) {
Settings.databaseType = type;
found = true;
break;
}
}
if (!found) {
plugin.getLogger().severe("Database type not found! Using FLATFILE");
Settings.databaseType = DatabaseType.FLATFILE;
}
Settings.dbHost = plugin.getConfig().getString("general.database.host", "localhost");
Settings.dbPort = plugin.getConfig().getInt("general.database.port",3306);
Settings.dbName = plugin.getConfig().getString("general.database.name", "BSkyBlock");
Settings.dbUsername = plugin.getConfig().getString("general.database.username");
Settings.dbPassword = plugin.getConfig().getString("general.database.password");
Settings.recoverSuperFlat = plugin.getConfig().getBoolean("general.recover-super-flat", false);
Settings.muteDeathMessages = plugin.getConfig().getBoolean("general.mute-death-messages", false);
//Settings.ftbAutoActivator = plugin.getConfig().getBoolean("general.FTB-auto-activator", false);
Settings.allowObsidianScooping = plugin.getConfig().getBoolean("general.allow-obsidian-scooping", true);
// Allow teleport
//Settings.fallingAllowTeleport = plugin.getConfig().getBoolean("general.allow-teleport.falling", true);
//Settings.fallingBlockedCommands = plugin.getConfig().getStringList("general.allow-teleport.falling-blocked-commands");
//Settings.acidAllowTeleport = plugin.getConfig().getBoolean("general.allow-teleport.acid", true);
//Settings.acidBlockedCommands = plugin.getConfig().getStringList("general.allow-teleport.acid-blocked-commands");
// ********************* World *********************
Settings.worldName = plugin.getConfig().getString("world.world-name", "BSkyBlock_world");
//TODO check if it is the same than before
int distance = plugin.getConfig().getInt("world.distance", 208);
Settings.islandDistance = Math.round((long)distance/16) * 16;
if(distance < 48) errors.put(ConfigError.ISLAND_DISTANCE_TOO_LOW, Settings.islandDistance);
Settings.islandProtectionRange = plugin.getConfig().getInt("world.protection-range", 100);
if(Settings.islandProtectionRange < 0) errors.put(ConfigError.PROTECTION_RANGE_TOO_LOW, Settings.islandProtectionRange);
if(Settings.islandProtectionRange > Settings.islandDistance) errors.put(ConfigError.PROTECTION_RANGE_HIGHER_THAN_ISLAND_DISTANCE, Settings.islandProtectionRange);
//Settings.startX = plugin.getConfig().getInt("world.start-x", 0);
//Settings.startZ = plugin.getConfig().getInt("world.start-z", 0);
Settings.islandHeight = plugin.getConfig().getInt("world.island-height", 120);
if(Settings.islandHeight < 5) errors.put(ConfigError.ISLAND_HEIGHT_TOO_LOW, Settings.islandHeight);
Settings.seaHeight = plugin.getConfig().getInt("world.sea-height", 0);
Settings.maxIslands = plugin.getConfig().getInt("world.max-islands", 0);
// Nether
Settings.netherGenerate = plugin.getConfig().getBoolean("world.nether.generate", true);
Settings.netherIslands = plugin.getConfig().getBoolean("world.nether.islands", true);
Settings.netherTrees = plugin.getConfig().getBoolean("world.nether.trees", true);
Settings.netherRoof = plugin.getConfig().getBoolean("world.nether.roof", true);
Settings.netherSpawnRadius = plugin.getConfig().getInt("world.nether.spawn-radius", 25);
if(!Settings.netherIslands){
// If the nether is vanilla
if(Settings.netherSpawnRadius < 0) errors.put(ConfigError.NETHER_SPAWN_RADIUS_TOO_LOW, Settings.netherSpawnRadius);
if(Settings.netherSpawnRadius > 100) errors.put(ConfigError.NETHER_SPAWN_RADIUS_TOO_HIGH, Settings.netherSpawnRadius);
}
// TODO: add to config
Settings.endGenerate = true;
Settings.endIslands = false;
Settings.limitedBlocks = new HashMap<>();
Settings.defaultWorldSettings = new HashMap<>();
// Team
Settings.maxTeamSize = plugin.getConfig().getInt("island.max-team-size", 4);
//Settings.leaveConfirmation = plugin.getConfig().getBoolean("require-confirmation.leave", true);
//Settings.leaveConfirmWait = plugin.getConfig().getLong("require-confirmation.leave-wait", 10) * 20;
//TODO end loading
//TODO not setup error report
return true;
}
public static void loadLocales(BSkyBlock plugin){
//TODO Imperatively load en-US locale
}
}

View File

@ -1,181 +0,0 @@
package us.tastybento.bskyblock.config;
import java.util.HashMap;
import java.util.List;
import org.bukkit.entity.EntityType;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffectType;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.database.BSBDatabase.DatabaseType;
/**
* All the plugin settings are here
* @author Tastybento
*/
public class Settings {
/* The settings variables should follow the config order */
// Constants
// Game Type BSKYBLOCK or ACIDISLAND
public enum GameType {
BSKYBLOCK, ACIDISLAND
}
/*
public final static GameType GAMETYPE = GameType.ACIDISLAND;
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
// Permission prefix
public final static String PERMPREFIX = "acidisland.";
// The island command
public final static String ISLANDCOMMAND = "ai";
// The challenge command
public static final String CHALLENGECOMMAND = "aic";
// Admin command
public static final String ADMINCOMMAND = "acid";
*/
public final static GameType GAMETYPE = GameType.BSKYBLOCK;
// Permission prefix
public final static String PERMPREFIX = "bskyblock.";
// The island command
public final static String ISLANDCOMMAND = "island";
// The challenge command
public static final String CHALLENGECOMMAND = "bsc";
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
// Admin command
public static final String ADMINCOMMAND = "bsadmin";
/* GENERAL */
public static boolean metrics;
public static boolean checkUpdates;
public static String defaultLanguage;
public static boolean useEconomy;
public static double startingMoney;
// Purge
public static int purgeMaxIslandLevel;
public static boolean purgeRemoveUserData;
// TODO Database
public static int databaseBackupPeriod;
public static boolean recoverSuperFlat;
public static boolean muteDeathMessages;
public static boolean allowAutoActivator;
public static boolean allowObsidianScooping;
/* WORLD */
public static String worldName;
public static int islandDistance;
public static int islandProtectionRange;
public static int islandStartX;
public static int islandStartZ;
public static int islandXOffset;
public static int islandZOffset;
public static int seaHeight;
public static int islandHeight;
public static int maxIslands;
// Nether
public static boolean netherGenerate;
public static boolean netherIslands;
public static boolean netherTrees;
public static boolean netherRoof;
public static int netherSpawnRadius;
// Entities
public static int spawnLimitMonsters;
public static int spawnLimitAnimals;
public static HashMap<EntityType, Integer> entityLimits;
public static HashMap<String, Integer> tileEntityLimits;
/* ISLAND */
public static int maxTeamSize;
public static int maxHomes;
public static int nameMinLength;
public static int nameMaxLength;
public static int inviteWait;
// Reset
public static int resetLimit;
public static int resetWait;
public static boolean leaversLoseReset;
public static boolean kickedKeepInventory;
public static boolean onJoinResetMoney;
public static boolean onJoinResetInventory;
public static boolean onJoinResetEnderChest;
public static boolean onLeaveResetMoney;
public static boolean onLeaveResetInventory;
public static boolean onLeaveResetEnderChest;
// Remove mobs
public static boolean removeMobsOnLogin;
public static boolean removeMobsOnIsland;
public static List<String> removeMobsWhitelist;
public static boolean makeIslandIfNone;
public static boolean immediateTeleportOnIsland;
public static boolean respawnOnIsland;
// Deaths
public static int deathsMax;
public static boolean deathsSumTeam;
/* PROTECTION */
public static boolean allowPistonPush;
public static boolean restrictWither;
// Invincible visitors
public static boolean invincibleVisitor;
public static List<DamageCause> invincibleVisitorOptions;
public static int togglePvPCooldown;
//TODO flags
/* ACID */
public static boolean acidDamageOp;
public static boolean acidDamageChickens;
// Damage
public static int acidDamage;
public static int acidDestroyItemTime;
public static int acidRainDamage;
public static List<PotionEffectType> acidEffects;
/* SCHEMATICS */
public static List<String> companionNames;
public static ItemStack[] chestItems;
public static EntityType companionType;
// Database settings
public static DatabaseType databaseType;
public static String dbHost;
public static int dbPort;
public static String dbName;
public static String dbUsername;
public static String dbPassword;
public static boolean useOwnGenerator;
public static boolean endGenerate;
public static boolean endIslands;
public static HashMap<Flag, Boolean> defaultWorldSettings;
public static boolean allowEndermanGriefing;
public static boolean endermanDeathDrop;
public static boolean allowTNTDamage;
public static boolean allowChestDamage;
public static boolean allowCreeperDamage;
public static boolean allowCreeperGriefing;
public static boolean allowMobDamageToItemFrames;
public static HashMap<String,Integer> limitedBlocks;
public static boolean allowTNTPushing;
public static boolean showInActionBar;
public static boolean teamJoinDeathReset;
}

View File

@ -1,8 +1,6 @@
package us.tastybento.bskyblock.database;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.database.flatfile.FlatFileDatabase;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.database.mysql.MySQLDatabase;
@ -16,7 +14,7 @@ public abstract class BSBDatabase {
*/
public static BSBDatabase getDatabase(){
for(DatabaseType type : DatabaseType.values()){
if(type == Settings.databaseType) return type.database;
if(type == BSkyBlock.getInstance().getSettings().getDatabaseType()) return type.database;
}
return DatabaseType.FLATFILE.database;
}
@ -38,6 +36,6 @@ public abstract class BSBDatabase {
* @param dataObjectClass
* @return database handler
*/
public abstract AbstractDatabaseHandler<?> getHandler(Plugin plugin, Class<?> dataObjectClass);
public abstract AbstractDatabaseHandler<?> getHandler(Class<?> dataObjectClass);
}

View File

@ -1,7 +1,5 @@
package us.tastybento.bskyblock.database;
import us.tastybento.bskyblock.config.Settings;
public class DatabaseConnectionSettingsImpl {
private String host;
private int port;
@ -25,14 +23,6 @@ public class DatabaseConnectionSettingsImpl {
this.password = password;
}
public DatabaseConnectionSettingsImpl() {
this.host = Settings.dbHost;
this.port = Settings.dbPort;
this.databaseName = Settings.dbName;
this.username = Settings.dbUsername;
this.password = Settings.dbPassword;
}
/**
* @return the host
*/

View File

@ -1,15 +1,14 @@
package us.tastybento.bskyblock.database.flatfile;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
public class FlatFileDatabase extends BSBDatabase{
@Override
public AbstractDatabaseHandler<?> getHandler(Plugin plugin, Class<?> type) {
return new FlatFileDatabaseHandler<>(plugin, type, new FlatFileDatabaseConnecter(plugin, null));
public AbstractDatabaseHandler<?> getHandler(Class<?> type) {
return new FlatFileDatabaseHandler<>(BSkyBlock.getInstance(), type, new FlatFileDatabaseConnecter(BSkyBlock.getInstance(), null));
}
}

View File

@ -44,7 +44,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
if (!fileName.endsWith(".yml")) {
fileName = fileName + ".yml";
}
File yamlFile = new File(dataFolder, tableName + File.separator + fileName);
File yamlFile = new File(plugin.getDataFolder(), tableName + File.separator + fileName);
YamlConfiguration config = null;
if (yamlFile.exists()) {
@ -77,21 +77,21 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
/**
* Saves a YAML file
*
* @param yamlFile
* @param yamlConfig
* @param fileName
*/
@Override
public void saveYamlFile(YamlConfiguration yamlFile, String tableName, String fileName) {
public void saveYamlFile(YamlConfiguration yamlConfig, String tableName, String fileName) {
if (!fileName.endsWith(".yml")) {
fileName = fileName + ".yml";
}
File tableFolder = new File(dataFolder, tableName);
File tableFolder = new File(plugin.getDataFolder(), tableName);
File file = new File(tableFolder, fileName);
if (!tableFolder.exists()) {
tableFolder.mkdirs();
}
try {
yamlFile.save(file);
yamlConfig.save(file);
} catch (Exception e) {
e.printStackTrace();
}

View File

@ -17,12 +17,18 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
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.Constants;
import us.tastybento.bskyblock.Constants.GameType;
import us.tastybento.bskyblock.api.configuration.Adapter;
import us.tastybento.bskyblock.api.configuration.ConfigEntry;
import us.tastybento.bskyblock.api.configuration.StoreAt;
import us.tastybento.bskyblock.database.DatabaseConnecter;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.util.Util;
@ -39,6 +45,8 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
private static final String DATABASE_FOLDER_NAME = "database";
private static final boolean DEBUG = false;
private boolean configFlag;
public FlatFileDatabaseHandler(Plugin plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
super(plugin, type, databaseConnecter);
}
@ -70,13 +78,20 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@Override
public T loadObject(String key) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException {
YamlConfiguration config = databaseConnecter.loadYamlFile(type.getSimpleName(), key);
String path = DATABASE_FOLDER_NAME + File.separator + dataObject.getSimpleName();
String fileName = key;
StoreAt storeAt = dataObject.getAnnotation(StoreAt.class);
if (storeAt != null) {
path = storeAt.path();
fileName = storeAt.filename();
}
YamlConfiguration config = databaseConnecter.loadYamlFile(path, fileName);
return createObject(config);
}
@Override
public boolean objectExits(String key) {
return databaseConnecter.uniqueIdExists(type.getSimpleName(), key);
return databaseConnecter.uniqueIdExists(dataObject.getSimpleName(), key);
}
/**
@ -103,14 +118,23 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
}
};
String path = dataObject.getSimpleName();
StoreAt storeAt = dataObject.getAnnotation(StoreAt.class);
if (storeAt != null) {
path = storeAt.path();
}
File dataFolder = new File(plugin.getDataFolder(), DATABASE_FOLDER_NAME);
File tableFolder = new File(dataFolder, type.getSimpleName());
File tableFolder = new File(dataFolder, path);
if (!tableFolder.exists()) {
// Nothing there...
tableFolder.mkdirs();
}
for (File file: tableFolder.listFiles(ymlFilter)) {
YamlConfiguration config = databaseConnecter.loadYamlFile(type.getSimpleName(), file.getName());
String fileName = file.getName();
if (storeAt != null) {
fileName = storeAt.filename();
}
YamlConfiguration config = databaseConnecter.loadYamlFile(DATABASE_FOLDER_NAME + File.separator + dataObject.getSimpleName(), fileName);
list.add(createObject(config));
}
return list;
@ -131,15 +155,55 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws ClassNotFoundException
*/
private T createObject(YamlConfiguration config) throws InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
T instance = type.newInstance();
T instance = dataObject.newInstance();
for (Field field : type.getDeclaredFields()) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
// Run through all the fields in the object
for (Field field : dataObject.getDeclaredFields()) {
// Gets the getter and setters for this field
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the write method
Method method = propertyDescriptor.getWriteMethod();
if (DEBUG)
plugin.getLogger().info("DEBUG: " + field.getName() + ": " + propertyDescriptor.getPropertyType().getTypeName());
if (config.contains(field.getName())) {
String storageLocation = field.getName();
// Check if there is an annotation on the field
ConfigEntry configEntry = field.getAnnotation(ConfigEntry.class);
// If there is a config annotation then do something
if (configEntry != null) {
if (!configEntry.path().isEmpty()) {
storageLocation = configEntry.path();
}
if (!configEntry.specificTo().equals(GameType.BOTH) && !configEntry.specificTo().equals(Constants.GAMETYPE)) {
if (DEBUG)
Bukkit.getLogger().info(field.getName() + " not applicable to this game type");
continue;
}
// TODO: Add handling of other ConfigEntry elements
if (!configEntry.adapter().equals(Adapter.class)) {
// A conversion adapter has been defined
Object value = config.get(storageLocation);
method.invoke(instance, ((Adapter<?,?>)configEntry.adapter().newInstance()).convertFrom(value));
if (DEBUG) {
plugin.getLogger().info("DEBUG: value = " + value);
plugin.getLogger().info("DEBUG: property type = " + propertyDescriptor.getPropertyType());
plugin.getLogger().info("DEBUG: " + value.getClass());
}
if (value != null && !value.getClass().equals(MemorySection.class)) {
method.invoke(instance, deserialize(value,propertyDescriptor.getPropertyType()));
}
// We are done here
continue;
}
}
// Look in the YAML Config to see if this field exists (it should)
if (config.contains(storageLocation)) {
// Check for null values
if (config.get(storageLocation) == null) {
method.invoke(instance, (Object)null);
continue;
}
// Handle storage of maps. Check if this type is a Map
if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Note that we have no idea what type this is
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
@ -150,9 +214,9 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
plugin.getLogger().info("DEBUG: is Map or HashMap<" + keyType.getTypeName() + ", " + valueType.getTypeName() + ">");
// TODO: this may not work with all keys. Further serialization may be required.
Map<Object,Object> value = new HashMap<Object, Object>();
for (String key : config.getConfigurationSection(field.getName()).getKeys(false)) {
for (String key : config.getConfigurationSection(storageLocation).getKeys(false)) {
Object mapKey = deserialize(key,Class.forName(keyType.getTypeName()));
Object mapValue = deserialize(config.get(field.getName() + "." + key), Class.forName(valueType.getTypeName()));
Object mapValue = deserialize(config.get(storageLocation + "." + key), Class.forName(valueType.getTypeName()));
if (DEBUG) {
plugin.getLogger().info("DEBUG: mapKey = " + mapKey + " (" + mapKey.getClass().getCanonicalName() + ")");
plugin.getLogger().info("DEBUG: mapValue = " + mapValue + " (" + mapValue.getClass().getCanonicalName() + ")");
@ -177,13 +241,13 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
}
for (Object listValue: config.getList(field.getName())) {
for (Object listValue: config.getList(storageLocation)) {
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
((Set<Object>) value).add(deserialize(listValue,Class.forName(setType.getTypeName())));
}
// TODO: this may not work with all keys. Further serialization may be required.
//Set<Object> value = new HashSet((List<Object>) config.getList(field.getName()));
//Set<Object> value = new HashSet((List<Object>) config.getList(storageLocation));
method.invoke(instance, value);
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
//plugin.getLogger().info("DEBUG: is Set " + propertyDescriptor.getReadMethod().getGenericReturnType().getTypeName());
@ -197,22 +261,23 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
List<Object> value = new ArrayList<Object>();
//plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
//plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
for (Object listValue: config.getList(field.getName())) {
for (Object listValue: config.getList(storageLocation)) {
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
((List<Object>) value).add(deserialize(listValue,Class.forName(setType.getTypeName())));
}
// TODO: this may not work with all keys. Further serialization may be required.
//Set<Object> value = new HashSet((List<Object>) config.getList(field.getName()));
//Set<Object> value = new HashSet((List<Object>) config.getList(storageLocation));
method.invoke(instance, value);
} else {
// Not a collection
if (DEBUG)
plugin.getLogger().info("DEBUG: not a collection");
Object value = config.get(field.getName());
Object value = config.get(storageLocation);
if (DEBUG) {
plugin.getLogger().info("DEBUG: name = " + field.getName());
plugin.getLogger().info("DEBUG: value = " + value);
plugin.getLogger().info("DEBUG: property type = " + propertyDescriptor.getPropertyType());
plugin.getLogger().info("DEBUG: " + value.getClass());
plugin.getLogger().info("DEBUG: value class " + value.getClass());
}
if (value != null && !value.getClass().equals(MemorySection.class)) {
method.invoke(instance, deserialize(value,propertyDescriptor.getPropertyType()));
@ -224,6 +289,14 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
return instance;
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#saveConfig(java.lang.Object)
*/
public void saveSettings(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
configFlag = true;
saveObject(instance);
}
/**
* Inserts T into the corresponding database-table
*
@ -238,36 +311,70 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
public void saveObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
// This is the Yaml Configuration that will be used and saved at the end
YamlConfiguration config = new YamlConfiguration();
// The file name of the Yaml file.
String filename = "";
String path = DATABASE_FOLDER_NAME + File.separator + dataObject.getSimpleName();
// Only allow storing in an arbitrary place if it is a config object. Otherwise it is in the database
if (configFlag) {
StoreAt storeAt = instance.getClass().getAnnotation(StoreAt.class);
if (storeAt != null) {
path = storeAt.path();
filename = storeAt.filename();
}
}
// Run through all the fields in the class that is being stored. EVERY field must have a get and set method
for (Field field : type.getDeclaredFields()) {
for (Field field : dataObject.getDeclaredFields()) {
// Get the property descriptor for this field
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the read method, i.e., getXXXX();
Method method = propertyDescriptor.getReadMethod();
// Invoke the read method to get the value. We have no idea what type of value it is.
Object value = method.invoke(instance);
//plugin.getLogger().info("DEBUG: writing " + field.getName());
String storageLocation = field.getName();
// Check if there is an annotation on the field
ConfigEntry configEntry = field.getAnnotation(ConfigEntry.class);
// If there is a config path annotation then do something
if (configEntry != null) {
if (!configEntry.path().isEmpty()) {
storageLocation = configEntry.path();
}
// TODO: add in game-specific saving
if (!configEntry.adapter().equals(Adapter.class)) {
// A conversion adapter has been defined
try {
config.set(storageLocation, ((Adapter<?,?>)configEntry.adapter().newInstance()).convertTo(value));
} catch (InstantiationException e) {
e.printStackTrace();
}
// We are done here
continue;
}
}
//plugin.getLogger().info("DEBUG: property desc = " + propertyDescriptor.getPropertyType().getTypeName());
// Depending on the vale type, it'll need serializing differenty
// Check if this field is the mandatory UniqueId field. This is used to identify this instantiation of the class
if (method.getName().equals("getUniqueId")) {
// If the object does not have a unique name assigned to it already, one is created at random
// If the object does not have a unique name assigned to it already, one is created at random
//plugin.getLogger().info("DEBUG: uniqueId = " + value);
String id = (String)value;
if (id.isEmpty()) {
id = databaseConnecter.getUniqueId(type.getSimpleName());
if (value == null || id.isEmpty()) {
id = databaseConnecter.getUniqueId(dataObject.getSimpleName());
// Set it in the class so that it will be used next time
propertyDescriptor.getWriteMethod().invoke(instance, id);
}
// Save the name for when the file is saved
filename = id;
if (filename.isEmpty())
filename = id;
}
// Collections need special serialization
if (propertyDescriptor.getPropertyType().equals(HashMap.class) || propertyDescriptor.getPropertyType().equals(Map.class)) {
if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Maps need to have keys serialized
//plugin.getLogger().info("DEBUG: Map for " + field.getName());
//plugin.getLogger().info("DEBUG: Map for " + storageLocation);
if (value != null) {
Map<Object, Object> result = new HashMap<Object, Object>();
for (Entry<Object, Object> object : ((Map<Object,Object>)value).entrySet()) {
@ -276,31 +383,29 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
result.put(serialize(object.getKey()), object.getValue());
}
// Save the list in the config file
config.set(field.getName(), result);
config.set(storageLocation, result);
}
} else if (propertyDescriptor.getPropertyType().equals(Set.class)) {
} else if (Set.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Sets need to be serialized as string lists
if (DEBUG)
plugin.getLogger().info("DEBUG: Set for " + field.getName());
plugin.getLogger().info("DEBUG: Set for " + storageLocation);
if (value != null) {
List<Object> list = new ArrayList<Object>();
for (Object object : (Set<Object>)value) {
list.add(serialize(object));
}
// Save the list in the config file
config.set(field.getName(), list);
config.set(storageLocation, list);
}
} else {
// For all other data that doesn't need special serialization
config.set(field.getName(), serialize(value));
config.set(storageLocation, serialize(value));
}
}
if (filename.isEmpty()) {
throw new IllegalArgumentException("No uniqueId in class");
}
// Save the file in the right folder
databaseConnecter.saveYamlFile(config, type.getSimpleName(), filename);
databaseConnecter.saveYamlFile(config, path, filename);
}
/**
@ -379,18 +484,30 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@Override
public void deleteObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
// The file name of the Yaml file.
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", dataObject);
Method method = propertyDescriptor.getReadMethod();
String fileName = (String) method.invoke(instance);
if (!fileName.endsWith(".yml")) {
fileName = fileName + ".yml";
}
File dataFolder = new File(plugin.getDataFolder(), DATABASE_FOLDER_NAME);
File tableFolder = new File(dataFolder, type.getSimpleName());
File tableFolder = new File(dataFolder, dataObject.getSimpleName());
if (tableFolder.exists()) {
File file = new File(tableFolder, fileName);
file.delete();
}
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#loadSettings(java.lang.String, java.lang.Object)
*/
@Override
public T loadSettings(String uniqueId, T dbConfig) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException {
if (dbConfig == null) return loadObject(uniqueId);
// TODO: compare the loaded with the database copy
return loadObject(uniqueId);
}
}

View File

@ -19,10 +19,10 @@ import us.tastybento.bskyblock.database.DatabaseConnecter;
public abstract class AbstractDatabaseHandler<T> {
/**
* The type of the objects that should be created and filled with values
* The data object that should be created and filled with values
* from the database or inserted into the database
*/
protected Class<T> type;
protected Class<T> dataObject;
/**
* Contains the settings to create a connection to the database like
@ -52,7 +52,7 @@ public abstract class AbstractDatabaseHandler<T> {
protected AbstractDatabaseHandler(Plugin plugin, Class<T> type, DatabaseConnecter databaseConnecter) {
this.plugin = plugin;
this.databaseConnecter = databaseConnecter;
this.type = type;
this.dataObject = type;
this.selectQuery = createSelectQuery();
this.insertQuery = createInsertQuery();
this.deleteQuery = createDeleteQuery();
@ -132,4 +132,28 @@ public abstract class AbstractDatabaseHandler<T> {
*/
public abstract boolean objectExits(String key);
/**
* Saves a file as settings
* @param instance
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws IntrospectionException
*/
public abstract void saveSettings(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException;
/**
* Loads a file as settings
* @param uniqueId
* @param dbConfig - the database mirror of this object. It will be checked against what is loaded to see if any significant changes have been made
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws ClassNotFoundException
* @throws IntrospectionException
*/
public abstract T loadSettings(String uniqueId, T dbConfig) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException;
}

View File

@ -15,7 +15,7 @@ import org.bukkit.Location;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.database.objects.Players;
@ -42,7 +42,7 @@ public class PlayersManager{
this.plugin = plugin;
database = BSBDatabase.getDatabase();
// Set up the database handler to store and retrieve Players classes
handler = (AbstractDatabaseHandler<Players>) database.getHandler(plugin, Players.class);
handler = (AbstractDatabaseHandler<Players>) database.getHandler(Players.class);
playerCache = new HashMap<>();
inTeleport = new HashSet<>();
}
@ -138,7 +138,7 @@ public class PlayersManager{
} else {
if (DEBUG)
plugin.getLogger().info("DEBUG: new player");
player = new Players(playerUUID);
player = new Players(plugin, playerUUID);
}
playerCache.put(playerUUID, player);
return player;
@ -506,7 +506,7 @@ public class PlayersManager{
addPlayer(targetUUID);
// Check if the target player has a permission bypass (admin.noban)
Player target = plugin.getServer().getPlayer(targetUUID);
if (target != null && target.hasPermission(Settings.PERMPREFIX + "admin.noban")) {
if (target != null && target.hasPermission(Constants.PERMPREFIX + "admin.noban")) {
return false;
}
Island island = plugin.getIslands().getIsland(playerUUID);

View File

@ -17,7 +17,6 @@ import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.util.Util;
@ -136,7 +135,7 @@ public class IslandCache {
public Island createIsland(Location location, UUID owner){
if (DEBUG)
plugin.getLogger().info("DEBUG: adding island for " + owner + " at " + location);
Island island = new Island(location, owner, Settings.islandProtectionRange);
Island island = new Island(location, owner, plugin.getSettings().getIslandProtectionRange());
islandsByLocation.put(location, island);
if (owner != null)
islandsByUUID.put(owner, island);

View File

@ -20,12 +20,11 @@ import org.bukkit.material.TrapDoor;
import org.bukkit.util.Vector;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.generators.IslandWorld;
import us.tastybento.bskyblock.util.DeleteIslandChunks;
import us.tastybento.bskyblock.util.SafeSpotTeleport;
import us.tastybento.bskyblock.util.Util;
@ -50,7 +49,7 @@ public class IslandsManager {
* - Location to be checked
* @return true if safe, otherwise false
*/
public static boolean isSafeLocation(final Location l) {
public boolean isSafeLocation(final Location l) {
if (l == null) {
return false;
}
@ -76,7 +75,7 @@ public class IslandsManager {
// In BSkyBlock, liquid may be unsafe
if (ground.isLiquid() || space1.isLiquid() || space2.isLiquid()) {
// Check if acid has no damage
if (Settings.acidDamage > 0D) {
if (plugin.getSettings().getAcidDamage() > 0D) {
// Bukkit.getLogger().info("DEBUG: acid");
return false;
} else if (ground.getType().equals(Material.STATIONARY_LAVA) || ground.getType().equals(Material.LAVA)
@ -143,7 +142,7 @@ public class IslandsManager {
this.plugin = plugin;
database = BSBDatabase.getDatabase();
// Set up the database handler to store and retrieve Island classes
handler = (AbstractDatabaseHandler<Island>) database.getHandler(plugin, Island.class);
handler = (AbstractDatabaseHandler<Island>) database.getHandler(Island.class);
islandCache = new IslandCache();
spawn = null;
}
@ -248,7 +247,7 @@ public class IslandsManager {
public Island createIsland(Location location, UUID owner){
if (DEBUG)
plugin.getLogger().info("DEBUG: adding island for " + owner + " at " + location);
return islandCache.createIsland(new Island(location, owner, Settings.islandProtectionRange));
return islandCache.createIsland(new Island(location, owner, plugin.getSettings().getIslandProtectionRange()));
}
/**
@ -625,7 +624,7 @@ public class IslandsManager {
//player.sendBlockChange(home, Material.GLOWSTONE, (byte)0);
User user = User.getInstance(player);
if (number == 1) {
user.sendMessage("commands.island.go.teleport", "[label]", Settings.ISLANDCOMMAND);
user.sendMessage("commands.island.go.teleport", "[label]", Constants.ISLANDCOMMAND);
} else {
user.sendMessage("commands.island.go.island.go.teleported", "[number]", String.valueOf(number));
}
@ -696,7 +695,7 @@ public class IslandsManager {
if (plugin.getPlayers().hasIsland(uuid) || plugin.getPlayers().inTeam(uuid)) {
islandTestLocations.add(plugin.getIslands().getIslandLocation(uuid));
// If new Nether
if (Settings.netherGenerate && Settings.netherIslands && IslandWorld.getNetherWorld() != null) {
if (plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands() && plugin.getIslandWorldManager().getNetherWorld() != null) {
islandTestLocations.add(netherIsland(plugin.getIslands().getIslandLocation(uuid)));
}
}
@ -713,7 +712,7 @@ public class IslandsManager {
// Must be in the same world as the locations being checked
// Note that getWorld can return null if a world has been deleted on the server
if (islandTestLocation != null && islandTestLocation.getWorld() != null && islandTestLocation.getWorld().equals(loc.getWorld())) {
int protectionRange = Settings.islandProtectionRange;
int protectionRange = plugin.getSettings().getIslandProtectionRange();
if (getIslandAt(islandTestLocation) != null) {
// Get the protection range for this location if possible
Island island = getProtectedIslandAt(islandTestLocation);
@ -781,10 +780,10 @@ public class IslandsManager {
// Run through all the locations
for (Location islandTestLocation : islandTestLocations) {
if (loc.getWorld().equals(islandTestLocation.getWorld())) {
if (loc.getX() >= islandTestLocation.getX() - Settings.islandProtectionRange
&& loc.getX() < islandTestLocation.getX() + Settings.islandProtectionRange
&& loc.getZ() >= islandTestLocation.getZ() - Settings.islandProtectionRange
&& loc.getZ() < islandTestLocation.getZ() + Settings.islandProtectionRange) {
if (loc.getX() >= islandTestLocation.getX() - plugin.getSettings().getIslandProtectionRange()
&& loc.getX() < islandTestLocation.getX() + plugin.getSettings().getIslandProtectionRange()
&& loc.getZ() >= islandTestLocation.getZ() - plugin.getSettings().getIslandProtectionRange()
&& loc.getZ() < islandTestLocation.getZ() + plugin.getSettings().getIslandProtectionRange()) {
return true;
}
}
@ -807,7 +806,7 @@ public class IslandsManager {
*/
private Location netherIsland(Location islandLocation) {
//plugin.getLogger().info("DEBUG: netherworld = " + ASkyBlock.getNetherWorld());
return islandLocation.toVector().toLocation(IslandWorld.getNetherWorld());
return islandLocation.toVector().toLocation(plugin.getIslandWorldManager().getNetherWorld());
}
/**
@ -870,10 +869,10 @@ public class IslandsManager {
Island spawn = getSpawn();
if (spawn != null) {
// go to island spawn
player.teleport(IslandWorld.getIslandWorld().getSpawnLocation());
player.teleport(plugin.getIslandWorldManager().getIslandWorld().getSpawnLocation());
//plugin.getLogger().warning("During island deletion player " + player.getName() + " sent to spawn.");
} else {
if (!player.performCommand(Settings.SPAWNCOMMAND)) {
if (!player.performCommand(Constants.SPAWNCOMMAND)) {
plugin.getLogger().warning(
"During island deletion player " + player.getName() + " could not be sent to spawn so was dropped, sorry.");
}

View File

@ -10,9 +10,7 @@ import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.generators.IslandWorld;
import us.tastybento.bskyblock.island.builders.IslandBuilder;
import us.tastybento.bskyblock.island.builders.IslandBuilder.IslandType;
@ -23,13 +21,14 @@ import us.tastybento.bskyblock.island.builders.IslandBuilder.IslandType;
*/
public class NewIsland {
private static final boolean DEBUG = false;
private final BSkyBlock plugin = BSkyBlock.getInstance();
private BSkyBlock plugin;
private Island island;
private final Player player;
private final Reason reason;
private NewIsland(Island oldIsland, Player player, Reason reason) {
super();
this.plugin = BSkyBlock.getInstance();
this.player = player;
this.reason = reason;
newIsland();
@ -48,9 +47,10 @@ public class NewIsland {
/**
* Start building a new island
* @param plugin
* @return New island builder object
*/
public static Builder builder() {
public static Builder builder(BSkyBlock plugin) {
return new Builder();
}
@ -132,22 +132,22 @@ public class NewIsland {
plugin.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
// Create island
new IslandBuilder(island)
new IslandBuilder(plugin, island)
.setPlayer(player)
.setChestItems(Settings.chestItems)
.setChestItems(plugin.getSettings().getChestItems())
.setType(IslandType.ISLAND)
.build();
if (Settings.netherGenerate && Settings.netherIslands && IslandWorld.getNetherWorld() != null) {
new IslandBuilder(island)
if (plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands() && plugin.getIslandWorldManager().getNetherWorld() != null) {
new IslandBuilder(plugin,island)
.setPlayer(player)
.setChestItems(Settings.chestItems)
.setChestItems(plugin.getSettings().getChestItems())
.setType(IslandType.NETHER)
.build();
}
if (Settings.endGenerate && Settings.endIslands && IslandWorld.getEndWorld() != null) {
new IslandBuilder(island)
if (plugin.getSettings().isEndGenerate() && plugin.getSettings().isEndIslands() && plugin.getIslandWorldManager().getEndWorld() != null) {
new IslandBuilder(plugin,island)
.setPlayer(player)
.setChestItems(Settings.chestItems)
.setChestItems(plugin.getSettings().getChestItems())
.setType(IslandType.END)
.build();
}
@ -188,7 +188,8 @@ public class NewIsland {
// Find the next free spot
if (last == null) {
last = new Location(IslandWorld.getIslandWorld(), Settings.islandXOffset + Settings.islandStartX, Settings.islandHeight, Settings.islandZOffset + Settings.islandStartZ);
last = new Location(plugin.getIslandWorldManager().getIslandWorld(), plugin.getSettings().getIslandXOffset() + plugin.getSettings().getIslandStartX(),
plugin.getSettings().getIslandHeight(), plugin.getSettings().getIslandZOffset() + plugin.getSettings().getIslandStartZ());
}
Location next = last.clone();
if (DEBUG)
@ -218,25 +219,25 @@ public class NewIsland {
Location nextPos = lastIsland;
if (x < z) {
if (-1 * x < z) {
nextPos.setX(nextPos.getX() + Settings.islandDistance*2);
nextPos.setX(nextPos.getX() + plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
nextPos.setZ(nextPos.getZ() + Settings.islandDistance*2);
nextPos.setZ(nextPos.getZ() + plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
if (x > z) {
if (-1 * x >= z) {
nextPos.setX(nextPos.getX() - Settings.islandDistance*2);
nextPos.setX(nextPos.getX() - plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
nextPos.setZ(nextPos.getZ() - Settings.islandDistance*2);
nextPos.setZ(nextPos.getZ() - plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
if (x <= 0) {
nextPos.setZ(nextPos.getZ() + Settings.islandDistance*2);
nextPos.setZ(nextPos.getZ() + plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
nextPos.setZ(nextPos.getZ() - Settings.islandDistance*2);
nextPos.setZ(nextPos.getZ() - plugin.getSettings().getIslandDistance()*2);
return nextPos;
}
}

View File

@ -1,7 +1,6 @@
package us.tastybento.bskyblock.database.mysql;
import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.DatabaseConnectionSettingsImpl;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
@ -9,8 +8,15 @@ import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
public class MySQLDatabase extends BSBDatabase{
@Override
public AbstractDatabaseHandler<?> getHandler(Plugin plugin, Class<?> type) {
return new MySQLDatabaseHandler<>(plugin, type, new MySQLDatabaseConnecter(new DatabaseConnectionSettingsImpl()));
public AbstractDatabaseHandler<?> getHandler(Class<?> type) {
BSkyBlock plugin = BSkyBlock.getInstance();
return new MySQLDatabaseHandler<>(plugin, type, new MySQLDatabaseConnecter(new DatabaseConnectionSettingsImpl(
plugin.getSettings().getDbHost(),
plugin.getSettings().getDbPort(),
plugin.getSettings().getDbName(),
plugin.getSettings().getDbUsername(),
plugin.getSettings().getDbPassword()
)));
}
}

View File

@ -125,11 +125,11 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
private void createSchema() throws IntrospectionException, SQLException {
PreparedStatement pstmt = null;
try {
String sql = "CREATE TABLE IF NOT EXISTS `" + type.getCanonicalName() + "` (";
String sql = "CREATE TABLE IF NOT EXISTS `" + dataObject.getCanonicalName() + "` (";
// Run through the fields of the class using introspection
for (Field field : type.getDeclaredFields()) {
for (Field field : dataObject.getDeclaredFields()) {
// Get the description of the field
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
//plugin.getLogger().info("DEBUG: Field = " + field.getName() + "(" + propertyDescriptor.getPropertyType().getTypeName() + ")");
// Get default SQL mappings
// Get the write method for this field. This method will take an argument of the type of this field.
@ -152,7 +152,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
propertyDescriptor.getPropertyType().equals(HashMap.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// The ID in this table relates to the parent table and is unique
String setSql = "CREATE TABLE IF NOT EXISTS `" + type.getCanonicalName() + "." + field.getName() + "` ("
String setSql = "CREATE TABLE IF NOT EXISTS `" + dataObject.getCanonicalName() + "." + field.getName() + "` ("
+ "uniqueId VARCHAR(36) NOT NULL, ";
// Get columns separated by commas
setSql += getCollectionColumnString(writeMethod,false,true);
@ -207,7 +207,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
boolean first = true;
/* Iterate the column-names */
for (Field f : type.getDeclaredFields()) {
for (Field f : dataObject.getDeclaredFields()) {
if (first)
first = false;
else
@ -321,7 +321,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
sb.append(getColumns(false));
sb.append(" FROM ");
sb.append("`");
sb.append(type.getCanonicalName());
sb.append(dataObject.getCanonicalName());
sb.append("`");
return sb.toString();
@ -339,7 +339,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
sb.append("REPLACE INTO ");
sb.append("`");
// The table name is the canonical name, so that add-ons can be sure of a unique table in the database
sb.append(type.getCanonicalName());
sb.append(dataObject.getCanonicalName());
sb.append("`");
sb.append("(");
sb.append(getColumns(false));
@ -388,7 +388,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// insertQuery is created in super from the createInsertQuery() method
preparedStatement = connection.prepareStatement(insertQuery);
// Get the uniqueId. As each class extends DataObject, it must have this method in it.
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", dataObject);
Method getUniqueId = propertyDescriptor.getReadMethod();
final String uniqueId = (String) getUniqueId.invoke(instance);
if (DEBUG) {
@ -402,9 +402,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
if (DEBUG)
plugin.getLogger().info("DEBUG: insert Query " + insertQuery);
// Run through the fields in the class using introspection
for (Field field : type.getDeclaredFields()) {
for (Field field : dataObject.getDeclaredFields()) {
// Get the field's property descriptor
propertyDescriptor = new PropertyDescriptor(field.getName(), type);
propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the read method for this field
Method method = propertyDescriptor.getReadMethod();
if (DEBUG)
@ -421,14 +421,14 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// Collection
// The table is cleared for this uniqueId every time the data is stored
String clearTableSql = "DELETE FROM `" + type.getCanonicalName() + "." + field.getName() + "` WHERE uniqueId = ?";
String clearTableSql = "DELETE FROM `" + dataObject.getCanonicalName() + "." + field.getName() + "` WHERE uniqueId = ?";
PreparedStatement collStatement = connection.prepareStatement(clearTableSql);
collStatement.setString(1, uniqueId);
collStatement.execute();
if (DEBUG)
plugin.getLogger().info("DEBUG: collStatement " + collStatement.toString());
// Insert into the table
String setSql = "INSERT INTO `" + type.getCanonicalName() + "." + field.getName() + "` (uniqueId, ";
String setSql = "INSERT INTO `" + dataObject.getCanonicalName() + "." + field.getName() + "` (uniqueId, ";
// Get the columns we are going to insert, just the names of them
setSql += getCollectionColumnString(propertyDescriptor.getWriteMethod(), false, false) + ") ";
// Get all the ?'s for the columns
@ -602,7 +602,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
plugin.getLogger().info("DEBUG: loading object for " + uniqueId);
try {
connection = databaseConnecter.createConnection();
String query = "SELECT " + getColumns(false) + " FROM `" + type.getCanonicalName() + "` WHERE uniqueId = ? LIMIT 1";
String query = "SELECT " + getColumns(false) + " FROM `" + dataObject.getCanonicalName() + "` WHERE uniqueId = ? LIMIT 1";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, uniqueId);
if (DEBUG)
@ -653,18 +653,18 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Run through them one by one
while (resultSet.next()) {
// Create a new instance of this type
T instance = type.newInstance();
T instance = dataObject.newInstance();
// Get the unique ID from the results
String uniqueId = resultSet.getString("uniqueId");
if (uniqueId == null) {
throw new SQLException("No unique ID in the results!");
}
// Use introspection to run through all the fields in this type class
for (Field field : type.getDeclaredFields()) {
for (Field field : dataObject.getDeclaredFields()) {
/* We assume the table-column-names exactly match the variable-names of T */
Object value = resultSet.getObject(field.getName());
// Get the property descriptor of this type
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the write method for this field, because we are going to use it to write the value
// once we get the value from the database
Method method = propertyDescriptor.getWriteMethod();
@ -677,7 +677,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
String setSql = "SELECT ";
// Get the columns, just the names of them, no ?'s or types
setSql += getCollectionColumnString(method, false, false) + " ";
setSql += "FROM `" + type.getCanonicalName() + "." + field.getName() + "` ";
setSql += "FROM `" + dataObject.getCanonicalName() + "." + field.getName() + "` ";
// We will need to fill in the ? later with the unique id of the class from the database
setSql += "WHERE uniqueId = ?";
// Prepare the statement
@ -832,7 +832,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Try to connect to the database
connection = databaseConnecter.createConnection();
// Get the uniqueId. As each class extends DataObject, it must have this method in it.
Method getUniqueId = type.getMethod("getUniqueId");
Method getUniqueId = dataObject.getMethod("getUniqueId");
String uniqueId = (String) getUniqueId.invoke(instance);
//plugin.getLogger().info("DEBUG: Unique Id = " + uniqueId);
if (uniqueId.isEmpty()) {
@ -841,7 +841,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Delete from the main table
// First substitution is the table name
// deleteQuery is created in super from the createInsertQuery() method
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + type.getCanonicalName() + "`"));
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "`"));
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
@ -850,16 +850,16 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
preparedStatement.executeBatch();
// Delete from any sub tables created from the object
// Run through the fields in the class using introspection
for (Field field : type.getDeclaredFields()) {
for (Field field : dataObject.getDeclaredFields()) {
// Get the field's property descriptor
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Delete Collection tables
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(Map.class) ||
propertyDescriptor.getPropertyType().equals(HashMap.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// First substitution is the table name
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + type.getCanonicalName() + "." + field.getName() + "`"));
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "." + field.getName() + "`"));
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
@ -886,7 +886,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT IF ( EXISTS( SELECT * FROM `" + type.getCanonicalName() + "` WHERE `uniqueId` = ?), 1, 0)";
String query = "SELECT IF ( EXISTS( SELECT * FROM `" + dataObject.getCanonicalName() + "` WHERE `uniqueId` = ?), 1, 0)";
//String query = "SELECT * FROM `" + type.getCanonicalName() + "` WHERE uniqueId = ?";
try {
connection = databaseConnecter.createConnection();
@ -910,4 +910,18 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
return false;
}
@Override
public void saveSettings(T instance)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
plugin.getLogger().severe("This method should not be used because configs are not stored in MySQL");
}
@Override
public T loadSettings(String uniqueId, T dbConfig) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException {
plugin.getLogger().severe("This method should not be used because configs are not stored in MySQL");
return null;
}
}

View File

@ -1,20 +1,26 @@
package us.tastybento.bskyblock.database.objects;
import us.tastybento.bskyblock.BSkyBlock;
/**
* Contains fields that must be in any data object
* @author tastybento
*
*/
public abstract class DataObject {
public interface DataObject {
default BSkyBlock getPlugin() {
return BSkyBlock.getInstance();
}
/**
* @return the uniqueId
*/
public abstract String getUniqueId();
String getUniqueId();
/**
* @param uniqueId the uniqueId to set
*/
public abstract void setUniqueId(String uniqueId);
void setUniqueId(String uniqueId);
}

View File

@ -13,13 +13,13 @@ import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.IslandLockEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.IslandUnlockEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
/**
@ -30,11 +30,10 @@ import us.tastybento.bskyblock.util.Util;
* @author Tastybento
* @author Poslovitch
*/
public class Island extends DataObject {
public class Island implements DataObject {
private String uniqueId = "";
@Override
public String getUniqueId() {
// Island's have UUID's that are randomly assigned if they do not exist
if (uniqueId.isEmpty()) {
@ -43,7 +42,6 @@ public class Island extends DataObject {
return uniqueId;
}
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
@ -53,7 +51,7 @@ public class Island extends DataObject {
private Location center;
// Island range
private int range = Settings.islandDistance;
private int range;
// Coordinates of the island area
private int minX;
@ -104,7 +102,7 @@ public class Island extends DataObject {
private Location spawnPoint;
public Island() {}
public Island(Location location, UUID owner, int protectionRange) {
this.members.add(owner);
this.owner = owner;
@ -112,7 +110,7 @@ public class Island extends DataObject {
this.updatedDate = System.currentTimeMillis();
this.world = location.getWorld();
this.center = location;
this.range = Settings.islandDistance;
this.range = BSkyBlock.getInstance().getSettings().getIslandProtectionRange();
this.minX = center.getBlockX() - range;
this.minZ = center.getBlockZ() - range;
this.protectionRange = protectionRange;

View File

@ -9,14 +9,14 @@ import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.BSkyBlock;
/**
* Tracks the following info on the player
*
* @author tastybento
*/
public class Players extends DataObject {
public class Players implements DataObject {
private HashMap<Integer, Location> homeLocations;
private String uniqueId;
private String playerName;
@ -31,15 +31,16 @@ public class Players extends DataObject {
public Players() {}
/**
* @param plugin
* @param uniqueId
* Constructor - initializes the state variables
*
*/
public Players(final UUID uniqueId) {
public Players(BSkyBlock plugin, final UUID uniqueId) {
this.uniqueId = uniqueId.toString();
this.homeLocations = new HashMap<>();
this.playerName = "";
this.resetsLeft = Settings.resetLimit;
this.resetsLeft = plugin.getSettings().getResetLimit();
this.locale = "";
this.kickedList = new HashMap<>();
this.playerName = Bukkit.getServer().getOfflinePlayer(uniqueId).getName();
@ -200,8 +201,8 @@ public class Players extends DataObject {
*/
public void setDeaths(int deaths) {
this.deaths = deaths;
if (this.deaths > Settings.deathsMax) {
this.deaths = Settings.deathsMax;
if (this.deaths > getPlugin().getSettings().getDeathsMax()) {
this.deaths = getPlugin().getSettings().getDeathsMax();
}
}
@ -210,8 +211,8 @@ public class Players extends DataObject {
*/
public void addDeath() {
this.deaths++;
if (this.deaths > Settings.deathsMax) {
this.deaths = Settings.deathsMax;
if (this.deaths > getPlugin().getSettings().getDeathsMax()) {
this.deaths = getPlugin().getSettings().getDeathsMax();
}
}
@ -233,7 +234,7 @@ public class Players extends DataObject {
Calendar coolDownTime = Calendar.getInstance();
coolDownTime.setTime(kickedDate);
// coolDownTime.add(Calendar.HOUR_OF_DAY, Settings.inviteWait);
coolDownTime.add(Calendar.MINUTE, Settings.inviteWait);
coolDownTime.add(Calendar.MINUTE, getPlugin().getSettings().getInviteWait());
// Add the invite cooldown period
Calendar timeNow = Calendar.getInstance();
// plugin.getLogger().info("DEBUG: date now = " + timeNow);

View File

@ -11,16 +11,25 @@ import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.util.noise.PerlinOctaveGenerator;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.BSkyBlock;
/**
* @author tastybento
* Creates the world
*/
public class ChunkGeneratorWorld extends ChunkGenerator {
BSkyBlock plugin;
Random rand = new Random();
PerlinOctaveGenerator gen;
//BSkyBlock plugin = BSkyBlock.getPlugin();
/**
* @param plugin
*/
public ChunkGeneratorWorld(BSkyBlock plugin) {
super();
this.plugin = plugin;
}
@Override
public ChunkData generateChunkData(World world, Random random, int chunkX, int chunkZ, ChunkGenerator.BiomeGrid biomeGrid) {
@ -28,10 +37,10 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
return generateNetherChunks(world, random, chunkX, chunkZ, biomeGrid);
}
ChunkData result = createChunkData(world);
if (Settings.seaHeight != 0) {
if (plugin.getSettings().getSeaHeight() != 0) {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < Settings.seaHeight; y++) {
for (int y = 0; y < plugin.getSettings().getSeaHeight(); y++) {
result.setBlock(x, y, z, Material.STATIONARY_WATER);
}
}
@ -64,7 +73,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
if (!world.getEnvironment().equals(Environment.NETHER)) {
return result;
}
if (Settings.netherRoof) {
if (plugin.getSettings().isNetherRoof()) {
// Make the roof - common across the world
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {

View File

@ -6,11 +6,10 @@ import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.config.Settings;
public class IslandWorld {
//private BSkyBlock plugin;
private BSkyBlock plugin;
private static World islandWorld;
private static World netherWorld;
private static World endWorld;
@ -19,37 +18,38 @@ public class IslandWorld {
* Generates the Skyblock worlds.
*/
public IslandWorld(BSkyBlock plugin) {
if (Settings.useOwnGenerator) {
this.plugin = plugin;
if (plugin.getSettings().isUseOwnGenerator()) {
// Do nothing
return;
}
if (plugin.getServer().getWorld(Settings.worldName) == null) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName()) == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s Island World...");
}
// Create the world if it does not exist
islandWorld = WorldCreator.name(Settings.worldName).type(WorldType.FLAT).environment(World.Environment.NORMAL).generator(new ChunkGeneratorWorld())
islandWorld = WorldCreator.name(plugin.getSettings().getWorldName()).type(WorldType.FLAT).environment(World.Environment.NORMAL).generator(new ChunkGeneratorWorld(plugin))
.createWorld();
// Make the nether if it does not exist
if (Settings.netherGenerate) {
if (plugin.getServer().getWorld(Settings.worldName + "_nether") == null) {
if (plugin.getSettings().isNetherGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + "_nether") == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s Nether...");
}
if (!Settings.netherIslands) {
netherWorld = WorldCreator.name(Settings.worldName + "_nether").type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
if (!plugin.getSettings().isNetherIslands()) {
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_nether").type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
} else {
netherWorld = WorldCreator.name(Settings.worldName + "_nether").type(WorldType.FLAT).generator(new ChunkGeneratorWorld())
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_nether").type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
.environment(World.Environment.NETHER).createWorld();
}
}
// Make the end if it does not exist
if (Settings.endGenerate) {
if (plugin.getServer().getWorld(Settings.worldName + "_the_end") == null) {
if (plugin.getSettings().isEndGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + "_the_end") == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s End World...");
}
if (!Settings.endIslands) {
endWorld = WorldCreator.name(Settings.worldName + "_the_end").type(WorldType.NORMAL).environment(World.Environment.THE_END).createWorld();
if (!plugin.getSettings().isEndIslands()) {
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_the_end").type(WorldType.NORMAL).environment(World.Environment.THE_END).createWorld();
} else {
endWorld = WorldCreator.name(Settings.worldName + "_the_end").type(WorldType.FLAT).generator(new ChunkGeneratorWorld())
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_the_end").type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
.environment(World.Environment.THE_END).createWorld();
}
}
@ -62,22 +62,22 @@ public class IslandWorld {
Bukkit.getLogger().info("Trying to register generator with Multiverse ");
try {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + Settings.worldName + " normal -g " + plugin.getName());
"mv import " + plugin.getSettings().getWorldName() + " normal -g " + plugin.getName());
if (!Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + Settings.worldName)) {
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName())) {
Bukkit.getLogger().severe("Multiverse is out of date! - Upgrade to latest version!");
}
if (netherWorld != null && Settings.netherGenerate && Settings.netherIslands) {
if (netherWorld != null && plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + Settings.worldName + "_nether nether -g " + plugin.getName());
"mv import " + plugin.getSettings().getWorldName() + "_nether nether -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + Settings.worldName + "_nether");
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName() + "_nether");
}
if (endWorld != null && Settings.endGenerate && Settings.endIslands) {
if (endWorld != null && plugin.getSettings().isEndGenerate() && plugin.getSettings().isEndIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + Settings.worldName + "_the_end end -g " + plugin.getName());
"mv import " + plugin.getSettings().getWorldName() + "_the_end end -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + Settings.worldName + "_the_end");
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName() + "_the_end");
}
} catch (Exception e) {
Bukkit.getLogger().severe("Not successfull! Disabling " + plugin.getName() + "!");
@ -92,9 +92,9 @@ public class IslandWorld {
/**
* @return the islandWorld
*/
public static World getIslandWorld() {
if (Settings.useOwnGenerator) {
return Bukkit.getServer().getWorld(Settings.worldName);
public World getIslandWorld() {
if (plugin.getSettings().isUseOwnGenerator()) {
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName());
}
return islandWorld;
}
@ -102,9 +102,9 @@ public class IslandWorld {
/**
* @return the netherWorld
*/
public static World getNetherWorld() {
if (Settings.useOwnGenerator) {
return Bukkit.getServer().getWorld(Settings.worldName + "_nether");
public World getNetherWorld() {
if (plugin.getSettings().isUseOwnGenerator()) {
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + "_nether");
}
return netherWorld;
}
@ -112,9 +112,9 @@ public class IslandWorld {
/**
* @return the endWorld
*/
public static World getEndWorld() {
if (Settings.useOwnGenerator) {
return Bukkit.getServer().getWorld(Settings.worldName + "_the_end");
public World getEndWorld() {
if (plugin.getSettings().isUseOwnGenerator()) {
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + "_the_end");
}
return endWorld;
}

View File

@ -1,5 +1,6 @@
package us.tastybento.bskyblock.island.builders;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
@ -16,11 +17,11 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Chest;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.Constants.GameType;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.config.Settings.GameType;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.generators.IslandWorld;
/**
* Fired when a team event happens.
@ -40,13 +41,15 @@ public class IslandBuilder {
private World world;
private IslandType type = IslandType.ISLAND;
//private List<String> companionNames = new ArrayList<>();
private ItemStack[] chestItems;
private List<ItemStack> chestItems;
//private List<Entity> companions = new ArrayList<>();
private UUID playerUUID;
private String playerName;
private BSkyBlock plugin;
public IslandBuilder(Island island) {
public IslandBuilder(BSkyBlock plugin, Island island) {
super();
this.plugin = plugin;
this.island = island;
this.world = island.getWorld();
}
@ -59,13 +62,13 @@ public class IslandBuilder {
this.type = type;
switch(type) {
case END:
this.world = IslandWorld.getEndWorld();
this.world = plugin.getIslandWorldManager().getEndWorld();
break;
case ISLAND:
this.world = IslandWorld.getIslandWorld();
this.world = plugin.getIslandWorldManager().getIslandWorld();
break;
case NETHER:
this.world = IslandWorld.getNetherWorld();
this.world = plugin.getIslandWorldManager().getNetherWorld();
break;
default:
this.world = island.getWorld();
@ -87,10 +90,10 @@ public class IslandBuilder {
/**
* @param chestItems the default chestItems to set
* @param list the default chestItems to set
*/
public IslandBuilder setChestItems(ItemStack[] chestItems) {
this.chestItems = chestItems;
public IslandBuilder setChestItems(List<ItemStack> list) {
this.chestItems = list;
return this;
}
@ -98,7 +101,7 @@ public class IslandBuilder {
public void build() {
// Switch on island type
if (type == IslandType.ISLAND) {
if (Settings.GAMETYPE == GameType.ACIDISLAND) {
if (Constants.GAMETYPE == GameType.ACIDISLAND) {
generateAcidIslandBlocks();
} else {
generateIslandBlocks();
@ -494,7 +497,7 @@ public class IslandBuilder {
Chest chest = new Chest(BlockFace.SOUTH);
state.setData(chest);
state.update();
if (chestItems.length > 0) {
if (!chestItems.isEmpty()) {
InventoryHolder chestBlock = (InventoryHolder) state;
for (ItemStack item: chestItems) {
chestBlock.getInventory().addItem(item);

View File

@ -10,8 +10,8 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.managers.PlayersManager;
import us.tastybento.bskyblock.database.objects.Island;
@ -46,8 +46,8 @@ public class JoinLeaveListener implements Listener {
// Load player
players.addPlayer(playerUUID);
// Reset resets if the admin changes it to or from unlimited
if (Settings.resetLimit < players.getResetsLeft(playerUUID) || (Settings.resetLimit >= 0 && players.getResetsLeft(playerUUID) < 0)) {
players.setResetsLeft(playerUUID, Settings.resetLimit);
if (plugin.getSettings().getResetLimit() < players.getResetsLeft(playerUUID) || (plugin.getSettings().getResetLimit() >= 0 && players.getResetsLeft(playerUUID) < 0)) {
players.setResetsLeft(playerUUID, plugin.getSettings().getResetLimit());
}
if (DEBUG)
plugin.getLogger().info("DEBUG: Setting player's name");
@ -62,7 +62,7 @@ public class JoinLeaveListener implements Listener {
} else {
plugin.getLogger().warning("Player that just logged in has no name! " + playerUUID.toString());
}
if (Settings.removeMobsOnLogin) {
if (plugin.getSettings().isRemoveMobsOnLogin()) {
if (DEBUG)
plugin.getLogger().info("DEBUG: Removing mobs");
plugin.getIslands().removeMobs(player.getLocation());
@ -73,7 +73,7 @@ public class JoinLeaveListener implements Listener {
if (currentIsland != null && (currentIsland.isLocked() || plugin.getPlayers().isBanned(currentIsland.getOwner(),player.getUniqueId()))) {
if (DEBUG)
plugin.getLogger().info("DEBUG: Current island is locked, or player is banned");
if (!currentIsland.getMembers().contains(playerUUID) && !player.hasPermission(Settings.PERMPREFIX + "mod.bypassprotect")) {
if (!currentIsland.getMembers().contains(playerUUID) && !player.hasPermission(Constants.PERMPREFIX + "mod.bypassprotect")) {
if (DEBUG)
plugin.getLogger().info("DEBUG: No bypass - teleporting");
user.sendMessage("locked.islandlocked");

View File

@ -31,6 +31,7 @@ import us.tastybento.bskyblock.api.events.addon.AddonEvent;
public final class AddonsManager {
private static final boolean DEBUG = false;
private static final String LOCALE_FOLDER = "locales";
private List<Addon> addons;
private List<AddonClassLoader> loader;
private final Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
@ -132,10 +133,11 @@ public final class AddonsManager {
addon.setDataFolder(new File(f.getParent(), addon.getDescription().getName()));
addon.setAddonFile(f);
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER + File.separator + addon.getDescription().getName());
// Obtain any locale files and save them
for (String localeFile : listJarYamlFiles(jar, "locales")) {
//plugin.getLogger().info("DEBUG: saving " + localeFile + " from jar");
addon.saveResource(localeFile, plugin.getDataFolder(), false, true);
addon.saveResource(localeFile, localeDir, false, true);
}
plugin.getLocalesManager().loadLocales(addon.getDescription().getName());

View File

@ -1,13 +1,14 @@
package us.tastybento.bskyblock.managers;
import org.bukkit.Bukkit;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.api.panels.PanelItem;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.api.panels.PanelItem;
public final class FlagsManager {
private List<Flag> flags = new ArrayList<>();

View File

@ -2,13 +2,13 @@ package us.tastybento.bskyblock.managers;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.localization.BSBLocale;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.FileLister;
/**
@ -23,7 +23,7 @@ public final class LocalesManager {
public LocalesManager(BSkyBlock plugin) {
this.plugin = plugin;
this.loadLocales("BSB"); // Default
this.loadLocales("BSkyBlock"); // Default
}
/**
@ -37,8 +37,8 @@ public final class LocalesManager {
if (locale != null && locale.contains(reference))
return locale.get(reference);
// Return the default
if (languages.get(Locale.forLanguageTag(Settings.defaultLanguage)).contains(reference)) {
return languages.get(Locale.forLanguageTag(Settings.defaultLanguage)).get(reference);
if (languages.get(Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage())).contains(reference)) {
return languages.get(Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage())).get(reference);
}
return null;
}
@ -49,33 +49,45 @@ public final class LocalesManager {
* TODO: Make more robust. The file filter is fragile.
*/
public void loadLocales(String parent) {
if (DEBUG) {
plugin.getLogger().info("DEBUG: loading locale for " + parent);
}
// Describe the filter - we only want files that are correctly named
FilenameFilter ymlFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
//plugin.getLogger().info("DEBUG: filename = " + name + " parent = " + parent );
if (name.startsWith(parent) && name.toLowerCase().endsWith(".yml")) {
// See if this is a valid locale
if (name.length() < 9)
return false;
//Locale localeObject = Locale.forLanguageTag(name.substring(name.length() - 9, name.length() - 4));
// Files must be 9 chars long
if (name.toLowerCase().endsWith(".yml") && name.length() == 9) {
if (DEBUG)
plugin.getLogger().info("DEBUG: bsb locale filename = " + name);
return true;
}
}
return false;
}
};
// Run through the files and store the locales
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER + "/" + parent);
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER + File.separator + parent);
if (DEBUG)
plugin.getLogger().info("DEBUG: localeDir = " + localeDir.getAbsolutePath());
// If the folder does not exist, then make it and fill with the locale files from the jar
// If it does exist, then new files will NOT be written!
if (!localeDir.exists()) {
localeDir.mkdir();
localeDir.mkdirs();
FileLister lister = new FileLister(plugin);
try {
for (String name : lister.listJar(LOCALE_FOLDER)) {
plugin.saveResource(name,true);
// We cannot use Bukkit's saveResource, because we want it to go into a specific folder, so...
InputStream initialStream = plugin.getResource(name);
// Get the last part of the name
int lastIndex = name.lastIndexOf('/');
File targetFile = new File(localeDir, name.substring(lastIndex >= 0 ? lastIndex : 0, name.length()));
if (DEBUG)
plugin.getLogger().info("DEBUG: targetFile = " + targetFile.getAbsolutePath());
if (!targetFile.exists()) {
java.nio.file.Files.copy(initialStream, targetFile.toPath());
}
initialStream.close();
}
} catch (Exception e) {
e.printStackTrace();
@ -85,14 +97,18 @@ public final class LocalesManager {
// Store all the locales available
for (File language : localeDir.listFiles(ymlFilter)) {
if (DEBUG)
plugin.getLogger().info("DEBUG: parent = " + parent + " language = " + language.getName().substring(parent.isEmpty() ? 0 : parent.length() + 1, language.getName().length() - 4));
Locale localeObject = Locale.forLanguageTag(language.getName().substring(parent.isEmpty() ? 0 : parent.length() + 1, language.getName().length() - 4));
plugin.getLogger().info("DEBUG: parent = " + parent + " language = " + language.getName().substring(0, language.getName().length() - 4));
Locale localeObject = Locale.forLanguageTag(language.getName().substring(0, language.getName().length() - 4));
if (DEBUG)
plugin.getLogger().info("DEBUG: locale country found = " + localeObject.getCountry());
if (languages.containsKey(localeObject)) {
if (DEBUG)
plugin.getLogger().info("DEBUG: this locale is known");
// Merge into current language
languages.get(localeObject).merge(language);
} else {
if (DEBUG)
plugin.getLogger().info("DEBUG: this locale is not known - new language");
// New language
languages.put(localeObject, new BSBLocale(localeObject, language));
}

View File

@ -6,9 +6,7 @@ import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.generators.IslandWorld;
//import com.wasteofplastic.askyblock.nms.NMSAbstraction;
@ -42,12 +40,12 @@ public class DeleteIslandChunks {
for (int x = minXChunk; x <= maxXChunk; x++) {
for (int z = minZChunk; z<=maxZChunk; z++) {
world.regenerateChunk(x, z);
if (Settings.netherIslands && Settings.netherGenerate) {
IslandWorld.getNetherWorld().regenerateChunk(x, z);
if (plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands()) {
plugin.getIslandWorldManager().getNetherWorld().regenerateChunk(x, z);
}
if (Settings.endIslands && Settings.endGenerate) {
IslandWorld.getEndWorld().regenerateChunk(x, z);
if (plugin.getSettings().isEndGenerate() && plugin.getSettings().isEndIslands()) {
plugin.getIslandWorldManager().getEndWorld().regenerateChunk(x, z);
}
}
}

View File

@ -27,8 +27,6 @@ import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.generators.IslandWorld;
/**
* A set of utility methods
@ -37,9 +35,9 @@ import us.tastybento.bskyblock.generators.IslandWorld;
* @author Poslovitch
*/
public class Util {
private static BSkyBlock plugin = BSkyBlock.getInstance();
private static String serverVersion = null;
private static BSkyBlock plugin = BSkyBlock.getInstance();
/**
* Returns the server version
@ -209,13 +207,13 @@ public class Util {
*/
public static boolean inWorld(Location loc) {
if (loc != null) {
if (loc.getWorld().equals(IslandWorld.getIslandWorld())) {
if (loc.getWorld().equals(plugin.getIslandWorldManager().getIslandWorld())) {
return true;
}
if (Settings.netherIslands && loc.getWorld().equals(IslandWorld.getNetherWorld())) {
if (plugin.getSettings().isNetherIslands() && loc.getWorld().equals(plugin.getIslandWorldManager().getNetherWorld())) {
return true;
}
if (Settings.endIslands && loc.getWorld().equals(IslandWorld.getEndWorld())) {
if (plugin.getSettings().isEndIslands() && loc.getWorld().equals(plugin.getIslandWorldManager().getEndWorld())) {
return true;
}
}
@ -364,7 +362,7 @@ public class Util {
// In ASkyBlock, liquid may be unsafe
if (ground.isLiquid() || space1.isLiquid() || space2.isLiquid()) {
// Check if acid has no damage
if (Settings.acidDamage > 0D) {
if (plugin.getSettings().getAcidDamage() > 0D) {
// Bukkit.getLogger().info("DEBUG: acid");
return false;
} else if (ground.getType().equals(Material.STATIONARY_LAVA) || ground.getType().equals(Material.LAVA)

View File

@ -26,11 +26,11 @@ import org.junit.Test;
import org.mockito.Mockito;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.team.TeamEvent;
import us.tastybento.bskyblock.config.Settings;
import us.tastybento.bskyblock.util.Util;
public class TestBSkyBlock {
@ -56,7 +56,7 @@ public class TestBSkyBlock {
Mockito.when(Bukkit.getLogger()).thenReturn(Logger.getAnonymousLogger());
sender = mock(CommandSender.class);
player = mock(Player.class);
Mockito.when(player.hasPermission(Settings.PERMPREFIX + "default.permission")).thenReturn(true);
Mockito.when(player.hasPermission(Constants.PERMPREFIX + "default.permission")).thenReturn(true);
plugin = mock(BSkyBlock.class);
//Mockito.when(plugin.getServer()).thenReturn(server);
@ -81,7 +81,7 @@ public class TestBSkyBlock {
User user = User.getInstance(playerUUID);
CompositeCommand testCommand = new TestCommand();
testCommand.setOnlyPlayer(true);
testCommand.setPermission(Settings.PERMPREFIX + "default.permission");
testCommand.setPermission(Constants.PERMPREFIX + "default.permission");
// Test basic execution
assertTrue(testCommand.execute(user, new ArrayList<>()));
assertEquals("test",testCommand.getLabel());
@ -89,7 +89,7 @@ public class TestBSkyBlock {
assertEquals("t", testCommand.getAliases().get(0));
assertTrue(testCommand.isOnlyPlayer());
assertNull(testCommand.getParent());
assertEquals(Settings.PERMPREFIX + "default.permission", testCommand.getPermission());
assertEquals(Constants.PERMPREFIX + "default.permission", testCommand.getPermission());
// Check commands and aliases match to correct class
for (Entry<String, CompositeCommand> command : testCommand.getSubCommands().entrySet()) {
assertEquals(testCommand.getSubCommand(command.getKey()), Optional.of(command.getValue()));
@ -123,7 +123,7 @@ public class TestBSkyBlock {
// Test command arguments
CompositeCommand argCmd = new Test3ArgsCommand();
argCmd.setOnlyPlayer(true);
argCmd.setPermission(Settings.PERMPREFIX + "default.permission");
argCmd.setPermission(Constants.PERMPREFIX + "default.permission");
assertTrue(argCmd.execute(player, "args", new String[]{"give", "100", "ben"}));
assertFalse(testCommand.execute(player, "test", new String[] {"sub2", "subsub", "subsubsub"}));
assertFalse(testCommand.execute(player, "test", new String[] {"sub2", "subsub", "subsubsub", "ben"}));