Automated code cleanup.

Removes spaces, adds {} to if statements, etc.
This commit is contained in:
Tastybento 2018-02-08 20:08:46 -08:00
parent 98b49ea37a
commit c916bbf827
111 changed files with 1223 additions and 923 deletions

View File

@ -20,7 +20,7 @@ public class Constants {
public static final String ISLANDCOMMAND = "ai";
// Admin command
public static final String ADMINCOMMAND = "acid";
*/
*/
public static final GameType GAMETYPE = GameType.BSKYBLOCK;
// Permission prefix
public static final String PERMPREFIX = "bskyblock.";

View File

@ -96,7 +96,7 @@ public class Metrics {
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
@ -150,12 +150,7 @@ public class Metrics {
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
submitData();
}
});
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000*60*5L, 1000*60*30L);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
@ -250,17 +245,14 @@ public class Metrics {
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
new Thread(() -> {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
@ -283,7 +275,9 @@ public class Metrics {
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
if (compressedData == null) throw new Exception();
if (compressedData == null) {
throw new Exception();
}
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");

View File

@ -540,6 +540,7 @@ public class Settings implements ISettings<Settings> {
/**
* @return the uniqueId
*/
@Override
public String getUniqueId() {
return uniqueId;
}
@ -1207,6 +1208,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param uniqueId the uniqueId to set
*/
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}

View File

@ -16,8 +16,8 @@ import org.bukkit.event.Listener;
import us.tastybento.bskyblock.BSkyBlock;
/**
* Add-on class for BSkyBlock. Extend this to create an add-on.
* The operation and methods are very similar to Bukkit's JavaPlugin.
* Add-on class for BSkyBlock. Extend this to create an add-on. The operation
* and methods are very similar to Bukkit's JavaPlugin.
*
* @author tastybento, ComminQ_Q
*/
@ -32,10 +32,10 @@ public abstract class Addon implements AddonInterface {
private File file;
public Addon() {
this.enabled = false;
enabled = false;
}
public BSkyBlock getBSkyBlock(){
public BSkyBlock getBSkyBlock() {
return BSkyBlock.getInstance();
}
@ -77,6 +77,7 @@ public abstract class Addon implements AddonInterface {
/**
* Convenience method to obtain the server
*
* @return the server object
*/
public Server getServer() {
@ -89,6 +90,7 @@ public abstract class Addon implements AddonInterface {
/**
* Load a YAML file
*
* @param file
* @return Yaml File configuration
*/
@ -109,9 +111,10 @@ public abstract class Addon implements AddonInterface {
/**
* Register a listener for this addon
*
* @param listener
*/
public void registerListener(Listener listener){
public void registerListener(Listener listener) {
BSkyBlock.getInstance().getServer().getPluginManager().registerEvents(listener, BSkyBlock.getInstance());
}
@ -120,15 +123,15 @@ public abstract class Addon implements AddonInterface {
*/
public void saveConfig() {
try {
this.config.save(new File(dataFolder, ADDON_CONFIG_FILENAME));
config.save(new File(dataFolder, ADDON_CONFIG_FILENAME));
} catch (IOException e) {
Bukkit.getLogger().severe("Could not save config!");
}
}
/**
* Saves the addon's config.yml file to the addon's data folder and loads it.
* If the file exists already, it will not be replaced.
* Saves the addon's config.yml file to the addon's data folder and loads it. If
* the file exists already, it will not be replaced.
*/
public void saveDefaultConfig() {
saveResource(ADDON_CONFIG_FILENAME, false);
@ -136,20 +139,30 @@ public abstract class Addon implements AddonInterface {
}
/**
* Saves a resource contained in this add-on's jar file to the addon's data folder.
* @param resourcePath in jar file
* @param replace - if true, will overwrite previous file
* Saves a resource contained in this add-on's jar file to the addon's data
* folder.
*
* @param resourcePath
* in jar file
* @param replace
* - if true, will overwrite previous file
*/
public void saveResource(String resourcePath, boolean replace) {
saveResource(resourcePath, dataFolder, replace, false);
}
/**
* Saves a resource contained in this add-on's jar file to the destination folder.
* @param jarResource in jar file
* @param destinationFolder on file system
* @param replace - if true, will overwrite previous file
* @param noPath - if true, the resource's path will be ignored when saving
* Saves a resource contained in this add-on's jar file to the destination
* folder.
*
* @param jarResource
* in jar file
* @param destinationFolder
* on file system
* @param replace
* - if true, will overwrite previous file
* @param noPath
* - if true, the resource's path will be ignored when saving
*/
public void saveResource(String jarResource, File destinationFolder, boolean replace, boolean noPath) {
if (jarResource == null || jarResource.equals("")) {
@ -162,7 +175,8 @@ public abstract class Addon implements AddonInterface {
if (jarConfig != null) {
try (InputStream in = jar.getInputStream(jarConfig)) {
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + jarResource + "' cannot be found in " + jar.getName());
throw new IllegalArgumentException(
"The embedded resource '" + jarResource + "' cannot be found in " + jar.getName());
}
// There are two options, use the path of the resource or not
File outFile = new File(destinationFolder, jarResource);
@ -181,36 +195,42 @@ public abstract class Addon implements AddonInterface {
}
}
} catch (IOException e) {
Bukkit.getLogger().severe("Could not save from jar file. From " + jarResource + " to " + destinationFolder.getAbsolutePath());
Bukkit.getLogger().severe(
"Could not save from jar file. From " + jarResource + " to " + destinationFolder.getAbsolutePath());
}
}
/**
* Set the file that contains this addon
* @param f the file to set
*
* @param f
* the file to set
*/
public void setAddonFile(File f) {
this.file = f;
file = f;
}
/**
* Set this addon's data folder
*
* @param file
*/
public void setDataFolder(File file) {
this.dataFolder = file;
dataFolder = file;
}
/**
* Set this addons description
*
* @param desc
*/
public void setDescription(AddonDescription desc){
this.description = desc;
public void setDescription(AddonDescription desc) {
description = desc;
}
/**
* Set whether this addon is enabled or not
*
* @param enabled
*/
public void setEnabled(boolean enabled) {

View File

@ -20,55 +20,55 @@ import us.tastybento.bskyblock.managers.AddonsManager;
*/
public class AddonClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
private Addon addon;
private final Map<String, Class<?>> classes = new HashMap<>();
private Addon addon;
private AddonsManager loader;
public AddonClassLoader(AddonsManager addonsManager, Map<String, String>data, File path, ClassLoader parent)
throws InvalidAddonInheritException,
MalformedURLException,
InvalidAddonFormatException,
InvalidDescriptionException,
InstantiationException,
IllegalAccessException {
super(new URL[]{path.toURI().toURL()}, parent);
public AddonClassLoader(AddonsManager addonsManager, Map<String, String>data, File path, ClassLoader parent)
throws InvalidAddonInheritException,
MalformedURLException,
InvalidAddonFormatException,
InvalidDescriptionException,
InstantiationException,
IllegalAccessException {
super(new URL[]{path.toURI().toURL()}, parent);
this.loader = addonsManager;
loader = addonsManager;
Class<?> javaClass = null;
try {
//Bukkit.getLogger().info("data " + data.get("main"));
/*
Class<?> javaClass = null;
try {
//Bukkit.getLogger().info("data " + data.get("main"));
/*
for (Entry<String, String> en : data.entrySet()) {
Bukkit.getLogger().info(en.getKey() + " => " + en.getValue());
}*/
javaClass = Class.forName(data.get("main"), true, this);
if(data.get("main").contains("us.tastybento")){
throw new InvalidAddonFormatException("Packages declaration cannot start with 'us.tastybento'");
}
} catch (ClassNotFoundException e) {
BSkyBlock.getInstance().getLogger().severe("Could not load '" + path.getName() + "' in folder '" + path.getParent() + "'");
throw new InvalidDescriptionException("Invalid addon.yml");
}
javaClass = Class.forName(data.get("main"), true, this);
if(data.get("main").contains("us.tastybento")){
throw new InvalidAddonFormatException("Packages declaration cannot start with 'us.tastybento'");
}
} catch (ClassNotFoundException e) {
BSkyBlock.getInstance().getLogger().severe("Could not load '" + path.getName() + "' in folder '" + path.getParent() + "'");
throw new InvalidDescriptionException("Invalid addon.yml");
}
Class<? extends Addon> addonClass;
try{
addonClass = javaClass.asSubclass(Addon.class);
} catch(ClassCastException e){
throw new InvalidAddonInheritException("Main class doesn't not extends super class 'Addon'");
}
Class<? extends Addon> addonClass;
try{
addonClass = javaClass.asSubclass(Addon.class);
} catch(ClassCastException e){
throw new InvalidAddonInheritException("Main class doesn't not extends super class 'Addon'");
}
this.addon = addonClass.newInstance();
addon.setDescription(this.asDescription(data));
}
addon = addonClass.newInstance();
addon.setDescription(asDescription(data));
}
private AddonDescription asDescription(Map<String, String> data){
String[] authors = data.get("authors").split("\\,");
private AddonDescription asDescription(Map<String, String> data){
String[] authors = data.get("authors").split("\\,");
return new AddonDescriptionBuilder(data.get("name"))
.withVersion(data.get("version"))
.withAuthor(authors).build();
}
return new AddonDescriptionBuilder(data.get("name"))
.withVersion(data.get("version"))
.withAuthor(authors).build();
}
/* (non-Javadoc)

View File

@ -89,22 +89,22 @@ public final class AddonDescription {
}
public AddonDescriptionBuilder withAuthor(String... authors){
this.description.setAuthors(Arrays.asList(authors));
description.setAuthors(Arrays.asList(authors));
return this;
}
public AddonDescriptionBuilder withDescription(String desc){
this.description.setDescription(desc);
description.setDescription(desc);
return this;
}
public AddonDescriptionBuilder withVersion(String version){
this.description.setVersion(version);
description.setVersion(version);
return this;
}
public AddonDescription build(){
return this.description;
return description;
}
}

View File

@ -2,13 +2,13 @@ package us.tastybento.bskyblock.api.addons.exception;
public abstract class AddonException extends Exception {
/**
*
*/
private static final long serialVersionUID = 4203162022348693854L;
/**
*
*/
private static final long serialVersionUID = 4203162022348693854L;
public AddonException(String errorMessage){
super("AddonException : " + errorMessage);
}
public AddonException(String errorMessage){
super("AddonException : " + errorMessage);
}
}

View File

@ -6,25 +6,25 @@ import org.bukkit.Bukkit;
public class InvalidAddonFormatException extends AddonException {
/**
*
*/
private static final long serialVersionUID = 7741502900847049986L;
/**
*
*/
private static final long serialVersionUID = 7741502900847049986L;
public InvalidAddonFormatException(String errorMessage) {
super(errorMessage);
}
public InvalidAddonFormatException(String errorMessage) {
super(errorMessage);
}
@Override
public void printStackTrace(){
super.printStackTrace();
@Override
public void printStackTrace(){
super.printStackTrace();
System.out.println("");
System.out.println("");
Bukkit.getLogger().log(Level.WARNING, " Basic format : (addon.yml)");
Bukkit.getLogger().log(Level.WARNING, " main: path.to.your.MainClass");
Bukkit.getLogger().log(Level.WARNING, " name: <NameOfYourModule>");
Bukkit.getLogger().log(Level.WARNING, " authors: <AuthorA> | <AuthorA, AuthorB>");
Bukkit.getLogger().log(Level.WARNING, " version: YourVersion");
}
Bukkit.getLogger().log(Level.WARNING, " Basic format : (addon.yml)");
Bukkit.getLogger().log(Level.WARNING, " main: path.to.your.MainClass");
Bukkit.getLogger().log(Level.WARNING, " name: <NameOfYourModule>");
Bukkit.getLogger().log(Level.WARNING, " authors: <AuthorA> | <AuthorA, AuthorB>");
Bukkit.getLogger().log(Level.WARNING, " version: YourVersion");
}
}

View File

@ -2,13 +2,13 @@ package us.tastybento.bskyblock.api.addons.exception;
public class InvalidAddonInheritException extends AddonException {
/**
*
*/
private static final long serialVersionUID = -5847358994397613244L;
/**
*
*/
private static final long serialVersionUID = -5847358994397613244L;
public InvalidAddonInheritException(String errorMessage) {
super(errorMessage);
}
public InvalidAddonInheritException(String errorMessage) {
super(errorMessage);
}
}

View File

@ -71,14 +71,14 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/
public CompositeCommand(BSkyBlock plugin, String label, String... string) {
super(label);
this.setAliases(new ArrayList<>(Arrays.asList(string)));
this.parent = null;
setAliases(new ArrayList<>(Arrays.asList(string)));
parent = null;
setUsage("");
this.subCommandLevel = 0; // Top level
this.subCommands = new LinkedHashMap<>();
this.subCommandAliases = new LinkedHashMap<>();
this.setup();
if (!this.getSubCommand("help").isPresent() && !label.equals("help")) {
subCommandLevel = 0; // Top level
subCommands = new LinkedHashMap<>();
subCommandAliases = new LinkedHashMap<>();
setup();
if (!getSubCommand("help").isPresent() && !label.equals("help")) {
new DefaultHelpCommand(this);
}
}
@ -93,20 +93,20 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
public CompositeCommand(CompositeCommand parent, String label, String... aliases) {
super(label);
this.parent = parent;
this.subCommandLevel = parent.getLevel() + 1;
subCommandLevel = parent.getLevel() + 1;
// Add this sub-command to the parent
parent.getSubCommands().put(label, this);
this.setAliases(new ArrayList<>(Arrays.asList(aliases)));
this.subCommands = new LinkedHashMap<>();
this.subCommandAliases = new LinkedHashMap<>();
setAliases(new ArrayList<>(Arrays.asList(aliases)));
subCommands = new LinkedHashMap<>();
subCommandAliases = new LinkedHashMap<>();
// Add aliases to the parent for this command
for (String alias : aliases) {
parent.subCommandAliases.put(alias, this);
}
setUsage("");
this.setup();
setup();
// If this command does not define its own help class, then use the default help command
if (!this.getSubCommand("help").isPresent() && !label.equals("help")) {
if (!getSubCommand("help").isPresent() && !label.equals("help")) {
new DefaultHelpCommand(this);
}
if (DEBUG) {
@ -124,18 +124,18 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: top level command registering..." + label);
}
this.setAliases(new ArrayList<>(Arrays.asList(aliases)));
this.parent = null;
setAliases(new ArrayList<>(Arrays.asList(aliases)));
parent = null;
setUsage("");
this.subCommandLevel = 0; // Top level
this.subCommands = new LinkedHashMap<>();
this.subCommandAliases = new LinkedHashMap<>();
subCommandLevel = 0; // Top level
subCommands = new LinkedHashMap<>();
subCommandAliases = new LinkedHashMap<>();
// Register command if it is not already registered
if (getPlugin().getCommand(label) == null) {
getPlugin().getCommandsManager().registerCommand(this);
}
this.setup();
if (!this.getSubCommand("help").isPresent() && !label.equals("help")) {
setup();
if (!getSubCommand("help").isPresent() && !label.equals("help")) {
new DefaultHelpCommand(this);
}
}
@ -189,17 +189,17 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
private CompositeCommand getCommandFromArgs(String[] args) {
CompositeCommand subCommand = this;
// Run through any arguments
for (int i = 0; i < args.length; i++) {
for (String arg : args) {
// get the subcommand corresponding to the arg
if (subCommand.hasSubCommmands()) {
Optional<CompositeCommand> sub = subCommand.getSubCommand(args[i]);
Optional<CompositeCommand> sub = subCommand.getSubCommand(arg);
if (!sub.isPresent()) {
return subCommand;
}
// Step down one
subCommand = sub.orElse(subCommand);
// Set the label
subCommand.setLabel(args[i]);
subCommand.setLabel(arg);
} else {
// We are at the end of the walk
return subCommand;
@ -254,7 +254,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
@Override
public String getPermission() {
return this.permission;
return permission;
}
/**
@ -292,14 +292,18 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) return Optional.of(subCommands.get(label));
if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommands.get(label));
}
}
// Try aliases
for (Map.Entry<String, CompositeCommand> entry : subCommandAliases.entrySet()) {
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: alias " + entry.getKey());
}
if (entry.getKey().equalsIgnoreCase(label)) return Optional.of(subCommandAliases.get(label));
if (entry.getKey().equalsIgnoreCase(label)) {
return Optional.of(subCommandAliases.get(label));
}
}
return Optional.empty();
}
@ -396,8 +400,8 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
@Override
public Command setUsage(String usage) {
// Go up the chain
CompositeCommand parent = this.getParent();
this.usage = this.getLabel() + " " + usage;
CompositeCommand parent = getParent();
this.usage = getLabel() + " " + usage;
while (parent != null) {
this.usage = parent.getLabel() + " " + this.usage;
parent = parent.getParent();
@ -428,7 +432,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
return options;
}
// Add any tab completion from the subcommand
options.addAll(cmd.tabComplete(User.getInstance(sender), alias, new LinkedList<String>(Arrays.asList(args))).orElse(new ArrayList<>()));
options.addAll(cmd.tabComplete(User.getInstance(sender), alias, new LinkedList<>(Arrays.asList(args))).orElse(new ArrayList<>()));
// Add any sub-commands automatically
if (cmd.hasSubCommmands()) {
// Check if subcommands are visible to this sender

View File

@ -28,8 +28,8 @@ public class DefaultHelpCommand extends CompositeCommand {
@Override
public void setup() {
// Set the usage to what the parent's command is
this.setParameters(parent.getParameters());
this.setDescription(parent.getDescription());
setParameters(parent.getParameters());
setDescription(parent.getDescription());
}
@Override

View File

@ -44,8 +44,9 @@ public class User {
* @return user
*/
public static User getInstance(Player player) {
if (player == null)
if (player == null) {
return null;
}
if (users.containsKey(player.getUniqueId())) {
return users.get(player.getUniqueId());
}
@ -80,22 +81,22 @@ public class User {
private final CommandSender sender;
private User(CommandSender sender) {
this.player = null;
this.playerUUID = null;
player = null;
playerUUID = null;
this.sender = sender;
}
private User(Player player) {
this.player = player;
this.sender = player;
this.playerUUID = player.getUniqueId();
sender = player;
playerUUID = player.getUniqueId();
users.put(player.getUniqueId(), this);
}
private User(UUID playerUUID) {
this.player = Bukkit.getPlayer(playerUUID);
player = Bukkit.getPlayer(playerUUID);
this.playerUUID = playerUUID;
this.sender = null;
sender = null;
}
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
@ -160,7 +161,9 @@ public class User {
String translation = plugin.getLocalesManager().get(this, reference);
// If no translation has been found, return the reference for debug purposes.
if (translation == null) return reference;
if (translation == null) {
return reference;
}
// Then replace variables
if (variables.length > 1) {
@ -251,8 +254,9 @@ public class User {
*/
public Locale getLocale() {
if (sender instanceof Player) {
if (!plugin.getPlayers().getLocale(this.playerUUID).isEmpty())
return Locale.forLanguageTag(plugin.getPlayers().getLocale(this.playerUUID));
if (!plugin.getPlayers().getLocale(playerUUID).isEmpty()) {
return Locale.forLanguageTag(plugin.getPlayers().getLocale(playerUUID));
}
}
return Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage());

View File

@ -41,11 +41,11 @@ public interface ISettings<T> {
@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());
AbstractDatabaseHandler<T> dbhandler = (AbstractDatabaseHandler<T>) BSBDatabase.getDatabase().getHandler(getClass());
T dbConfig = null;
if (dbhandler.objectExits(this.getUniqueId())) {
// Load it
dbConfig = dbhandler.loadObject(getUniqueId());
dbConfig = dbhandler.loadObject(getUniqueId());
}
// Get the handler
AbstractDatabaseHandler<T> configHandler = (AbstractDatabaseHandler<T>) new FlatFileDatabase().getHandler(getInstance().getClass());

View File

@ -23,9 +23,9 @@ public class IslandBaseEvent extends PremadeEvent implements Cancellable {
public IslandBaseEvent(Island island) {
super();
this.island = island;
this.playerUUID = island == null ? null : island.getOwner();
this.admin = false;
this.location = island == null ? null : island.getCenter();
playerUUID = island == null ? null : island.getOwner();
admin = false;
location = island == null ? null : island.getCenter();
}
/**
@ -46,14 +46,14 @@ public class IslandBaseEvent extends PremadeEvent implements Cancellable {
* @return the island involved in this event
*/
public Island getIsland(){
return this.island;
return island;
}
/**
* @return the owner of the island
*/
public UUID getOwner() {
return this.getOwner();
return getOwner();
}
/**
@ -84,6 +84,6 @@ public class IslandBaseEvent extends PremadeEvent implements Cancellable {
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
cancelled = cancel;
}
}

View File

@ -57,14 +57,14 @@ public class AddonEvent {
public AddonBaseEvent build() {
switch (reason) {
case ENABLE:
return new AddonEnableEvent(addon);
case DISABLE:
return new AddonDisableEvent(addon);
case LOAD:
return new AddonLoadEvent(addon);
default:
return new AddonGeneralEvent(addon);
case ENABLE:
return new AddonEnableEvent(addon);
case DISABLE:
return new AddonDisableEvent(addon);
case LOAD:
return new AddonLoadEvent(addon);
default:
return new AddonGeneralEvent(addon);
}
}
}

View File

@ -43,13 +43,13 @@ public class FlagChangeEvent extends IslandBaseEvent {
* @return the edited flag
*/
public Flag getFlag() {
return this.editedFlag;
return editedFlag;
}
/**
* @return enabled/disabled
*/
public boolean getSetTo() {
return this.setTo;
return setTo;
}
}

View File

@ -143,7 +143,7 @@ public class IslandEvent {
}
public IslandEventBuilder location(Location center) {
this.location = center;
location = center;
return this;
}

View File

@ -35,14 +35,14 @@ public class PurgeStartEvent extends PremadeEvent implements Cancellable {
* @return the user who launched the purge, may be null if purge is launched using the console.
*/
public UUID getUser( ){
return this.user;
return user;
}
/**
* @return the list of islands to remove, based on their leader's UUID
*/
public List<UUID> getIslandsList() {
return this.islandsList;
return islandsList;
}
/**
@ -50,7 +50,9 @@ public class PurgeStartEvent extends PremadeEvent implements Cancellable {
* @param - the owner's UUID from the island to remove
*/
public void add(UUID islandOwner) {
if(!this.islandsList.contains(islandOwner)) islandsList.add(islandOwner);
if(!islandsList.contains(islandOwner)) {
islandsList.add(islandOwner);
}
}
/**
@ -58,7 +60,9 @@ public class PurgeStartEvent extends PremadeEvent implements Cancellable {
* @param - the owner's UUID from the island to remove
*/
public void remove(UUID islandOwner) {
if(this.islandsList.contains(islandOwner)) islandsList.remove(islandOwner);
if(islandsList.contains(islandOwner)) {
islandsList.remove(islandOwner);
}
}
/**
@ -76,6 +80,6 @@ public class PurgeStartEvent extends PremadeEvent implements Cancellable {
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
cancelled = cancel;
}
}

View File

@ -134,7 +134,7 @@ public class TeamEvent {
}
public TeamEventBuilder location(Location center) {
this.location = center;
location = center;
return this;
}

View File

@ -20,7 +20,7 @@ public class Flag implements Comparable<Flag> {
private boolean defaultSetting;
public Flag(String id2, PanelItem icon, Listener listener, boolean defaultSetting, FlagType type) {
this.id = id2;
id = id2;
this.icon = icon;
this.listener = listener;
this.type = type;

View File

@ -17,7 +17,7 @@ public class FlagBuilder {
private FlagType type = FlagType.PROTECTION;
public FlagBuilder id(String string) {
this.id = string;
id = string;
return this;
}
@ -49,7 +49,7 @@ public class FlagBuilder {
* @return
*/
public FlagBuilder allowedByDefault(boolean setting) {
this.defaultSetting = setting;
defaultSetting = setting;
return this;
}
@ -69,7 +69,7 @@ public class FlagBuilder {
* @return
*/
public FlagBuilder id(Enum<?> flag) {
this.id = flag.name();
id = flag.name();
return this;
}
}

View File

@ -15,7 +15,7 @@ public class BSBLocale {
public BSBLocale(Locale locale, File file) {
this.locale = locale;
this.config = YamlConfiguration.loadConfiguration(file);
config = YamlConfiguration.loadConfiguration(file);
}
/**
@ -35,7 +35,9 @@ public class BSBLocale {
* @return the locale language
*/
public String getLanguage(){
if(locale == null) return "unknown";
if(locale == null) {
return "unknown";
}
return locale.getDisplayLanguage();
}
@ -45,7 +47,9 @@ public class BSBLocale {
* @return the locale country
*/
public String getCountry(){
if(locale == null) return "unknown";
if(locale == null) {
return "unknown";
}
return locale.getDisplayCountry();
}
@ -55,7 +59,7 @@ public class BSBLocale {
* @return the locale language tag
*/
public String toLanguageTag(){
return this.locale.toLanguageTag();
return locale.toLanguageTag();
}
/**

View File

@ -32,9 +32,9 @@ public class PanelItem {
this.clickHandler = clickHandler;
// Create the final item
this.setName(name);
this.setDescription(description);
this.setGlow(glow);
setName(name);
setDescription(description);
setGlow(glow);
// Set flags to neaten up the view
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
@ -78,10 +78,11 @@ public class PanelItem {
public void setGlow(boolean glow) {
this.glow = glow;
if (glow)
if (glow) {
meta.addEnchant(Enchantment.ARROW_DAMAGE, 0, true);
else
} else {
meta.addEnchant(Enchantment.ARROW_DAMAGE, 0, false);
}
}
/**

View File

@ -27,12 +27,12 @@ public class PanelBuilder {
* @return PanelBuilder
*/
public PanelBuilder addItem(int slot, PanelItem item) {
this.items.put(slot, item);
items.put(slot, item);
return this;
}
public int nextSlot() {
if (this.items.isEmpty()) {
if (items.isEmpty()) {
return 0;
} else {
return items.lastEntry().getKey() + 1;
@ -45,7 +45,7 @@ public class PanelBuilder {
* @return true or false
*/
public boolean slotOccupied(int slot) {
return this.items.containsKey(slot);
return items.containsKey(slot);
}
/**
@ -63,9 +63,9 @@ public class PanelBuilder {
*/
public PanelBuilder addItem(PanelItem item) {
if (items.isEmpty()) {
this.items.put(0, item);
items.put(0, item);
} else {
this.items.put(items.lastEntry().getKey() + 1, item);
items.put(items.lastEntry().getKey() + 1, item);
}
return this;
}

View File

@ -29,8 +29,8 @@ public class PanelItemBuilder {
}
public PanelItemBuilder name(String name) {
this.name = name;
return this;
this.name = name;
return this;
}
public PanelItemBuilder description(List<String> description) {
@ -59,8 +59,9 @@ public class PanelItemBuilder {
}
public PanelItem build() {
if (icon == null)
if (icon == null) {
Bukkit.getLogger().info("DEBUG: icon is null");
}
return new PanelItem(icon, name, description, glow, clickHandler);
}

View File

@ -17,9 +17,9 @@ public class AdminCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "admin.*");
this.setOnlyPlayer(false);
this.setDescription("admin.help.description");
setPermission(Constants.PERMPREFIX + "admin.*");
setOnlyPlayer(false);
setDescription("admin.help.description");
new AdminVersionCommand(this);
new AdminReloadCommand(this);
new AdminTeleportCommand(this);

View File

@ -27,10 +27,10 @@ public class IslandCommand extends CompositeCommand {
*/
@Override
public void setup() {
this.setDescription("commands.island.help.description");
this.setOnlyPlayer(true);
setDescription("commands.island.help.description");
setOnlyPlayer(true);
// Permission
this.setPermission(Constants.PERMPREFIX + "island");
setPermission(Constants.PERMPREFIX + "island");
// Set up subcommands
new IslandAboutCommand(this);
new IslandCreateCommand(this);
@ -47,12 +47,12 @@ public class IslandCommand extends CompositeCommand {
public boolean execute(User user, List<String> args) {
// If this player does not have an island, create one
if (!getPlugin().getIslands().hasIsland(user.getUniqueId())) {
Optional<CompositeCommand> subCreate = this.getSubCommand("create");
Optional<CompositeCommand> subCreate = getSubCommand("create");
if (subCreate.isPresent()) {
subCreate.get().execute(user, new ArrayList<>());
}
}
Optional<CompositeCommand> go = this.getSubCommand("go");
Optional<CompositeCommand> go = getSubCommand("go");
// Otherwise, currently, just go home
if (go.isPresent()) {
go.get().execute(user, new ArrayList<>());

View File

@ -18,9 +18,9 @@ public class AdminTeleportCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "admin.tp");
this.setOnlyPlayer(true);
this.setDescription("commands.admin.tp.description");
setPermission(Constants.PERMPREFIX + "admin.tp");
setOnlyPlayer(true);
setDescription("commands.admin.tp.description");
}
@Override
@ -38,9 +38,9 @@ public class AdminTeleportCommand extends CompositeCommand {
} else {
if (getPlayers().hasIsland(targetUUID) || getPlayers().inTeam(targetUUID)) {
Location warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getIslandWorld());
if (this.getLabel().equals("tpnether")) {
if (getLabel().equals("tpnether")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getNetherWorld());
} else if (this.getLabel().equals("tpend")) {
} else if (getLabel().equals("tpend")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getEndWorld());
}
// Other wise, go to a safe spot

View File

@ -15,7 +15,7 @@ public class AdminVersionCommand extends CompositeCommand {
@Override
public void setup() {
// Permission
this.setPermission(Constants.PERMPREFIX + "admin.version");
setPermission(Constants.PERMPREFIX + "admin.version");
}
@Override

View File

@ -23,11 +23,11 @@ public class CustomIslandMultiHomeHelp extends CompositeCommand {
@Override
public void setup() {
this.setOnlyPlayer(true);
setOnlyPlayer(true);
// Inherit parameters from the respective parent class - in this case, only /island go and /island sethome
this.setParameters(parent.getParameters());
this.setDescription(parent.getDescription());
this.setPermission(parent.getPermission());
setParameters(parent.getParameters());
setDescription(parent.getDescription());
setPermission(parent.getPermission());
}
@Override

View File

@ -18,7 +18,7 @@ public class IslandAboutCommand extends CompositeCommand {
@Override
public void setup() {
this.setDescription("commands.island.about.description");
setDescription("commands.island.about.description");
}
@Override

View File

@ -26,9 +26,9 @@ public class IslandCreateCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.create");
this.setOnlyPlayer(true);
this.setDescription("commands.island.create.description");
setPermission(Constants.PERMPREFIX + "island.create");
setOnlyPlayer(true);
setDescription("commands.island.create.description");
}
/* (non-Javadoc)

View File

@ -26,9 +26,9 @@ public class IslandGoCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.home");
this.setOnlyPlayer(true);
this.setDescription("commands.island.go.description");
setPermission(Constants.PERMPREFIX + "island.home");
setOnlyPlayer(true);
setDescription("commands.island.go.description");
new CustomIslandMultiHomeHelp(this);
}

View File

@ -23,9 +23,9 @@ public class IslandResetCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.create");
this.setOnlyPlayer(true);
this.setDescription("commands.island.reset.description");
setPermission(Constants.PERMPREFIX + "island.create");
setOnlyPlayer(true);
setDescription("commands.island.reset.description");
}
@Override
@ -46,15 +46,18 @@ public class IslandResetCommand extends CompositeCommand {
player.setGameMode(GameMode.SPECTATOR);
// Get the player's old island
Island oldIsland = getIslands().getIsland(player.getUniqueId());
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: old island is at " + oldIsland.getCenter().getBlockX() + "," + oldIsland.getCenter().getBlockZ());
}
// Remove them from this island (it still exists and will be deleted later)
getIslands().removePlayer(player.getUniqueId());
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: old island's owner is " + oldIsland.getOwner());
}
// Create new island and then delete the old one
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: making new island ");
}
try {
NewIsland.builder(getPlugin())
.player(player)

View File

@ -22,9 +22,9 @@ public class IslandResetnameCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.name");
this.setOnlyPlayer(true);
this.setDescription("commands.island.resetname.description");
setPermission(Constants.PERMPREFIX + "island.name");
setOnlyPlayer(true);
setDescription("commands.island.resetname.description");
}

View File

@ -16,9 +16,9 @@ public class IslandSethomeCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.sethome");
this.setOnlyPlayer(true);
this.setDescription("commands.island.sethome.description");
setPermission(Constants.PERMPREFIX + "island.sethome");
setOnlyPlayer(true);
setDescription("commands.island.sethome.description");
new CustomIslandMultiHomeHelp(this);
}

View File

@ -26,10 +26,10 @@ public class IslandSetnameCommand extends CompositeCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.name");
this.setOnlyPlayer(true);
this.setParameters("commands.island.setname.parameters");
this.setDescription("commands.island.setname.description");
setPermission(Constants.PERMPREFIX + "island.name");
setOnlyPlayer(true);
setParameters("commands.island.setname.parameters");
setDescription("commands.island.setname.description");
}
/* (non-Javadoc)
@ -69,9 +69,11 @@ public class IslandSetnameCommand extends CompositeCommand {
}
// Set the name
if (!player.hasPermission(Constants.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);
} else {
getIslands().getIsland(playerUUID).setName(name);
}
user.sendMessage("general.success");
return true;

View File

@ -23,9 +23,9 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.description");
new IslandTeamInviteCommand(this);
new IslandTeamLeaveCommand(this);
@ -36,17 +36,20 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
@Override
public boolean execute(User user, List<String> args) {
UUID playerUUID = user.getUniqueId();
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: executing team command for " + playerUUID);
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(playerUUID))
.getIsland(playerUUID))
.reason(TeamEvent.Reason.INFO)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return true;
if (event.isCancelled()) {
return true;
}
UUID teamLeaderUUID = getTeamLeader(user);
Set<UUID> teamMembers = getMembers(user);
if (teamLeaderUUID.equals(playerUUID)) {
@ -69,7 +72,9 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
}
}
// Do some sanity checking
if (maxSize < 1) maxSize = 1;
if (maxSize < 1) {
maxSize = 1;
}
}
if (teamMembers.size() < maxSize) {

View File

@ -21,9 +21,9 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.accept.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.invite.accept.description");
}
@Override
@ -32,8 +32,9 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
Bukkit.getLogger().info("DEBUG: accept - " + inviteList.toString());
UUID playerUUID = user.getUniqueId();
if(!inviteList.containsKey(playerUUID))
return false;
if(!inviteList.containsKey(playerUUID)) {
return false;
}
// Check if player has been invited
if (!inviteList.containsKey(playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.none-invited-you");
@ -51,20 +52,24 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
inviteList.remove(playerUUID);
return false;
}
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: Invite is valid");
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(prospectiveTeamLeaderUUID))
.getIsland(prospectiveTeamLeaderUUID))
.reason(TeamEvent.Reason.JOIN)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return true;
if (event.isCancelled()) {
return true;
}
// Remove the invite
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: Removing player from invite list");
}
inviteList.remove(playerUUID);
// Put player into Spectator mode
user.setGameMode(GameMode.SPECTATOR);
@ -100,8 +105,9 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
inviter.sendMessage("commands.island.team.invite.accept.name-joined-your-island", "[name]", user.getName());
}
getIslands().save(false);
if (DEBUG)
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: After save " + getIslands().getIsland(prospectiveTeamLeaderUUID).getMemberSet().toString());
}
return true;
}

View File

@ -27,9 +27,9 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.invite.description");
new IslandTeamInviteAcceptCommand(this);
new IslandTeamInviteRejectCommand(this);
@ -106,7 +106,9 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
}
}
// Do some sanity checking
if (maxSize < 1) maxSize = 1;
if (maxSize < 1) {
maxSize = 1;
}
}
if (teamMembers.size() < maxSize) {
// If that player already has an invite out then retract it.
@ -122,7 +124,9 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
.involvedPlayer(invitedPlayerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return true;
if (event.isCancelled()) {
return true;
}
// Put the invited player (key) onto the list with inviter (value)
// If someone else has invited a player, then this invite will overwrite the previous invite!
inviteList.put(invitedPlayerUUID, playerUUID);

View File

@ -16,9 +16,9 @@ public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.invite.reject.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.invite.reject.description");
}
@Override
@ -29,12 +29,14 @@ public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
.island(getIslands()
.getIsland(inviteList.get(playerUUID)))
.getIsland(inviteList.get(playerUUID)))
.reason(TeamEvent.Reason.REJECT)
.involvedPlayer(playerUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return false;
if (event.isCancelled()) {
return false;
}
// Remove this player from the global invite list
inviteList.remove(user.getUniqueId());

View File

@ -20,10 +20,10 @@ public class IslandTeamKickCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setParameters("commands.island.team.kick.parameters");
this.setDescription("commands.island.team.kick.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setParameters("commands.island.team.kick.parameters");
setDescription("commands.island.team.kick.description");
kickSet = new HashSet<>();
}

View File

@ -20,9 +20,9 @@ public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setDescription("commands.island.team.leave.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setDescription("commands.island.team.leave.description");
leaveSet = new HashSet<>();
}

View File

@ -13,10 +13,10 @@ public class IslandTeamPromoteCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setParameters("commands.island.team.promote.parameters");
this.setDescription("commands.island.team.promote.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setParameters("commands.island.team.promote.parameters");
setDescription("commands.island.team.promote.description");
}
@Override

View File

@ -24,10 +24,10 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
@Override
public void setup() {
this.setPermission(Constants.PERMPREFIX + "island.team");
this.setOnlyPlayer(true);
this.setParameters("commands.island.team.setowner.parameters");
this.setDescription("commands.island.team.setowner.description");
setPermission(Constants.PERMPREFIX + "island.team");
setOnlyPlayer(true);
setParameters("commands.island.team.setowner.parameters");
setDescription("commands.island.team.setowner.description");
}
@Override
@ -75,7 +75,9 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
.involvedPlayer(targetUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return false;
if (event.isCancelled()) {
return false;
}
// target is the new leader
getIslands().getIsland(playerUUID).setOwner(targetUUID);

View File

@ -14,7 +14,9 @@ public abstract class BSBDatabase {
*/
public static BSBDatabase getDatabase(){
for(DatabaseType type : DatabaseType.values()){
if(type == BSkyBlock.getInstance().getSettings().getDatabaseType()) return type.database;
if(type == BSkyBlock.getInstance().getSettings().getDatabaseType()) {
return type.database;
}
}
return DatabaseType.FLATFILE.database;
}

View File

@ -41,6 +41,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
* @param fileName
* @return
*/
@Override
public YamlConfiguration loadYamlFile(String tableName, String fileName) {
if (!fileName.endsWith(".yml")) {
fileName = fileName + ".yml";

View File

@ -109,16 +109,13 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@Override
public List<T> loadObjects() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException {
List<T> list = new ArrayList<T>();
FilenameFilter ymlFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".yml")) {
return true;
} else {
return false;
}
List<T> list = new ArrayList<>();
FilenameFilter ymlFilter = (dir, name) -> {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".yml")) {
return true;
} else {
return false;
}
};
String path = dataObject.getSimpleName();
@ -166,8 +163,9 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the write method
Method method = propertyDescriptor.getWriteMethod();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + field.getName() + ": " + propertyDescriptor.getPropertyType().getTypeName());
}
String storageLocation = field.getName();
// Check if there is an annotation on the field
ConfigEntry configEntry = field.getAnnotation(ConfigEntry.class);
@ -177,16 +175,18 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
storageLocation = configEntry.path();
}
if (!configEntry.specificTo().equals(GameType.BOTH) && !configEntry.specificTo().equals(Constants.GAMETYPE)) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info(field.getName() + " not applicable to this game type");
}
continue;
}
// TODO: Add handling of other ConfigEntry elements
}
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: there is an adapter");
}
// A conversion adapter has been defined
Object value = config.get(storageLocation);
method.invoke(instance, ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).serialize(value));
@ -216,10 +216,11 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// collectionTypes should be 2 long
Type keyType = collectionTypes.get(0);
Type valueType = collectionTypes.get(1);
if (DEBUG)
if (DEBUG) {
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>();
Map<Object,Object> value = new HashMap<>();
for (String key : config.getConfigurationSection(storageLocation).getKeys(false)) {
// Keys cannot be null - skip if they exist
Object mapKey = deserialize(key,Class.forName(keyType.getTypeName()));
@ -245,16 +246,17 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
// collectionTypes should be only 1 long
Type setType = collectionTypes.get(0);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: is HashSet<" + setType.getTypeName() + ">");
Set<Object> value = new HashSet<Object>();
}
Set<Object> value = new HashSet<>();
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
}
for (Object listValue: config.getList(storageLocation)) {
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
((Set<Object>) value).add(deserialize(listValue,Class.forName(setType.getTypeName())));
value.add(deserialize(listValue,Class.forName(setType.getTypeName())));
}
// TODO: this may not work with all keys. Further serialization may be required.
@ -262,27 +264,29 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
method.invoke(instance, value);
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
//plugin.getLogger().info("DEBUG: is Set " + propertyDescriptor.getReadMethod().getGenericReturnType().getTypeName());
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding a set");
}
// Loop through the collection resultset
// Note that we have no idea what type this is
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
// collectionTypes should be only 1 long
Type setType = collectionTypes.get(0);
List<Object> value = new ArrayList<Object>();
List<Object> value = new ArrayList<>();
//plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
//plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
for (Object listValue: config.getList(storageLocation)) {
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
((List<Object>) value).add(deserialize(listValue,Class.forName(setType.getTypeName())));
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(storageLocation));
method.invoke(instance, value);
} else {
// Not a collection
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: not a collection");
}
Object value = config.get(storageLocation);
if (DEBUG) {
plugin.getLogger().info("DEBUG: name = " + field.getName());
@ -303,6 +307,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#saveConfig(java.lang.Object)
*/
@Override
public void saveSettings(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
configFlag = true;
saveObject(instance);
@ -368,8 +373,9 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: there is an adapter");
}
// A conversion adapter has been defined
try {
config.set(storageLocation, ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).deserialize(value));
@ -393,15 +399,16 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
propertyDescriptor.getWriteMethod().invoke(instance, id);
}
// Save the name for when the file is saved
if (filename.isEmpty())
if (filename.isEmpty()) {
filename = id;
}
}
// Collections need special serialization
if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Maps need to have keys serialized
//plugin.getLogger().info("DEBUG: Map for " + storageLocation);
if (value != null) {
Map<Object, Object> result = new HashMap<Object, Object>();
Map<Object, Object> result = new HashMap<>();
for (Entry<Object, Object> object : ((Map<Object,Object>)value).entrySet()) {
// Serialize all key types
// TODO: also need to serialize values?
@ -412,10 +419,11 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
} else if (Set.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Sets need to be serialized as string lists
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Set for " + storageLocation);
}
if (value != null) {
List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>();
for (Object object : (Set<Object>)value) {
list.add(serialize(object));
}
@ -463,8 +471,9 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
if (DEBUG) {
plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getCanonicalName());
plugin.getLogger().info("DEBUG: value is " + value);
if (value != null)
if (value != null) {
plugin.getLogger().info("DEBUG: value class is " + value.getClass().getCanonicalName());
}
}
// If value is already null, then it can be nothing else
if (value == null) {
@ -537,7 +546,9 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@Override
public T loadSettings(String uniqueId, T dbConfig) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException {
if (dbConfig == null) return loadObject(uniqueId);
if (dbConfig == null) {
return loadObject(uniqueId);
}
// TODO: compare the loaded with the database copy

View File

@ -70,14 +70,16 @@ public class PlayersManager{
* @param async - if true, save async
*/
public void save(boolean async){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving " + async);
}
Collection<Players> set = Collections.unmodifiableCollection(playerCache.values());
if(async){
Runnable save = () -> {
for(Players player : set){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving player " + player.getPlayerName() + " "+ player.getUniqueId());
}
try {
handler.saveObject(player);
} catch (Exception e) {
@ -88,8 +90,9 @@ public class PlayersManager{
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, save);
} else {
for(Players player : set){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving player " + player.getPlayerName() + " "+ player.getUniqueId());
}
try {
handler.saveObject(player);
} catch (Exception e) {
@ -121,33 +124,39 @@ public class PlayersManager{
* @return the players object
*/
public Players addPlayer(final UUID playerUUID) {
if (playerUUID == null)
if (playerUUID == null) {
return null;
if (DEBUG)
}
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding player " + playerUUID);
}
if (!playerCache.containsKey(playerUUID)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: player not in cache");
}
Players player = null;
// If the player is in the database, load it, otherwise create a new player
if (handler.objectExits(playerUUID.toString())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: player in database");
}
try {
player = handler.loadObject(playerUUID.toString());
} catch (Exception e) {
plugin.getLogger().severe("Could not load player " + playerUUID + " " + e.getMessage());
}
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: new player");
}
player = new Players(plugin, playerUUID);
}
playerCache.put(playerUUID, player);
return player;
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: known player");
}
return playerCache.get(playerUUID);
}
}
@ -331,8 +340,9 @@ public class PlayersManager{
* @param name
*/
public void setPlayerName(User user) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Setting player name to " + user.getName() + " for " + user.getUniqueId());
}
addPlayer(user.getUniqueId());
playerCache.get(user.getUniqueId()).setPlayerName(user.getName());
}
@ -345,14 +355,16 @@ public class PlayersManager{
* @return String - playerName
*/
public String getName(UUID playerUUID) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Geting player name");
}
if (playerUUID == null) {
return "";
}
addPlayer(playerUUID);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: name is " + playerCache.get(playerUUID).getPlayerName());
}
return playerCache.get(playerUUID).getPlayerName();
}
@ -363,8 +375,9 @@ public class PlayersManager{
* @return UUID of owner of island
*/
public UUID getPlayerFromIslandLocation(Location loc) {
if (loc == null)
if (loc == null) {
return null;
}
// Look in the grid
Optional<Island> island = plugin.getIslands().getIslandAt(loc);
return island.map(x->x.getOwner()).orElse(null);
@ -425,7 +438,9 @@ public class PlayersManager{
*/
public String getLocale(UUID playerUUID) {
addPlayer(playerUUID);
if (playerUUID == null) return "";
if (playerUUID == null) {
return "";
}
return playerCache.get(playerUUID).getLocale();
}
@ -578,8 +593,9 @@ public class PlayersManager{
if (playerCache.containsKey(playerUUID)) {
final Players player = playerCache.get(playerUUID);
try {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving player by uuid " + player.getPlayerName() + " " + playerUUID + " saved");
}
handler.saveObject(player);
} catch (IllegalAccessException | IllegalArgumentException
@ -589,8 +605,9 @@ public class PlayersManager{
plugin.getLogger().severe("Could not save player to database: " + playerUUID + " " + e.getMessage());
}
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + playerUUID + " is not in the cache to save");
}
}
}

View File

@ -43,14 +43,17 @@ public class IslandCache {
*/
public void addIsland(Island island) {
islandsByLocation.put(island.getCenter(), island);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: owner = " + island.getOwner());
}
islandsByUUID.put(island.getOwner(), island);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: island has " + island.getMemberSet().size() + " members");
}
for (UUID member: island.getMemberSet()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + member);
}
islandsByUUID.put(member, island);
}
addToGrid(island);
@ -66,12 +69,14 @@ public class IslandCache {
*/
private void addToGrid(Island newIsland) {
if (islandGrid.containsKey(newIsland.getMinX())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: min x is in the grid :" + newIsland.getMinX());
}
TreeMap<Integer, Island> zEntry = islandGrid.get(newIsland.getMinX());
if (zEntry.containsKey(newIsland.getMinZ())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: min z is in the grid :" + newIsland.getMinZ());
}
// Island already exists
Island conflict = islandGrid.get(newIsland.getMinX()).get(newIsland.getMinZ());
plugin.getLogger().warning("*** Duplicate or overlapping islands! ***");
@ -94,17 +99,19 @@ public class IslandCache {
return;
} else {
// Add island
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: added island to grid at " + newIsland.getMinX() + "," + newIsland.getMinZ());
}
zEntry.put(newIsland.getMinZ(), newIsland);
islandGrid.put(newIsland.getMinX(), zEntry);
// plugin.getLogger().info("Debug: " + newIsland.toString());
}
} else {
// Add island
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: added island to grid at " + newIsland.getMinX() + "," + newIsland.getMinZ());
TreeMap<Integer, Island> zEntry = new TreeMap<Integer, Island>();
}
TreeMap<Integer, Island> zEntry = new TreeMap<>();
zEntry.put(newIsland.getMinZ(), newIsland);
islandGrid.put(newIsland.getMinX(), zEntry);
}
@ -117,8 +124,9 @@ public class IslandCache {
public Island createIsland(Island island) {
islandsByLocation.put(island.getCenter(), island);
if (island.getOwner() != null)
if (island.getOwner() != null) {
islandsByUUID.put(island.getOwner(), island);
}
addToGrid(island);
return island;
}
@ -137,12 +145,14 @@ public class IslandCache {
* @param owner UUID
*/
public Island createIsland(Location location, UUID owner){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding island for " + owner + " at " + location);
}
Island island = new Island(location, owner, plugin.getSettings().getIslandProtectionRange());
islandsByLocation.put(location, island);
if (owner != null)
if (owner != null) {
islandsByUUID.put(owner, island);
}
addToGrid(island);
return island;
}
@ -163,26 +173,31 @@ public class IslandCache {
}
}
// Remove from grid
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: deleting island at " + island.getCenter());
}
if (island != null) {
int x = island.getMinX();
int z = island.getMinZ();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: x = " + x + " z = " + z);
}
if (islandGrid.containsKey(x)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: x found");
}
TreeMap<Integer, Island> zEntry = islandGrid.get(x);
if (zEntry.containsKey(z)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: z found - deleting the island");
}
// Island exists - delete it
zEntry.remove(z);
islandGrid.put(x, zEntry);
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: could not find z");
}
}
}
}
@ -225,12 +240,14 @@ public class IslandCache {
// Check if in the island range
Island island = ent.getValue();
if (island.inIslandSpace(x, z)) {
if (DEBUG2)
if (DEBUG2) {
plugin.getLogger().info("DEBUG: In island space");
}
return island;
}
if (DEBUG2)
if (DEBUG2) {
plugin.getLogger().info("DEBUG: not in island space");
}
}
}
return null;
@ -264,8 +281,9 @@ public class IslandCache {
* @return Location of player's island or null if one does not exist
*/
public Location getIslandLocation(UUID playerUUID) {
if (hasIsland(playerUUID))
if (hasIsland(playerUUID)) {
return getIsland(playerUUID).getCenter();
}
return null;
}
@ -291,14 +309,16 @@ public class IslandCache {
public Set<UUID> getMembers(UUID playerUUID) {
Island island = islandsByUUID.get(playerUUID);
if (island != null)
return new HashSet<UUID>(island.getMemberSet());
return new HashSet<UUID>(0);
if (island != null) {
return new HashSet<>(island.getMemberSet());
}
return new HashSet<>(0);
}
public UUID getTeamLeader(UUID playerUUID) {
if (islandsByUUID.containsKey(playerUUID))
if (islandsByUUID.containsKey(playerUUID)) {
return islandsByUUID.get(playerUUID).getOwner();
}
return null;
}
@ -318,35 +338,41 @@ public class IslandCache {
}
}
if (islandsByUUID.containsKey(playerUUID) && islandsByUUID.get(playerUUID).getOwner() != null) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: checking for equals");
}
if (islandsByUUID.get(playerUUID).getOwner().equals(playerUUID)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: has island");
}
return true;
}
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: doesn't have island");
}
return false;
}
public void removePlayer(UUID playerUUID) {
Island island = islandsByUUID.get(playerUUID);
if (island != null) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: island found");
}
if (island.getOwner() != null && island.getOwner().equals(playerUUID)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: player is the owner of this island");
}
// Clear ownership and members
island.getMemberSet().clear();
island.setOwner(null);
}
island.getMemberSet().remove(playerUUID);
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: removing reference to island by UUID");
}
islandsByUUID.remove(playerUUID);
}

View File

@ -246,8 +246,9 @@ public class IslandsManager {
* @param owner UUID
*/
public Island createIsland(Location location, UUID owner){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding island for " + owner + " at " + location);
}
return islandCache.createIsland(new Island(location, owner, plugin.getSettings().getIslandProtectionRange()));
}
@ -257,8 +258,9 @@ public class IslandsManager {
* @param removeBlocks - if the island blocks should be removed or not
*/
public void deleteIsland(Island island, boolean removeBlocks) {
if (island == null)
if (island == null) {
return;
}
// Set the owner of the island to no one.
island.setOwner(null);
island.setLocked(false);
@ -291,8 +293,9 @@ public class IslandsManager {
*/
public void deleteIsland(final UUID player, boolean removeBlocks) {
// Removes the island
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: deleting player island");
}
//CoopPlay.getInstance().clearAllIslandCoops(player);
//getWarpSignsListener().removeWarp(player);
final Island island = getIsland(player);
@ -377,8 +380,9 @@ public class IslandsManager {
* @return Location of player's island or null if one does not exist
*/
public Location getIslandLocation(UUID playerUUID) {
if (hasIsland(playerUUID))
if (hasIsland(playerUUID)) {
return getIsland(playerUUID).getCenter();
}
return null;
}
@ -439,8 +443,9 @@ public class IslandsManager {
l = plugin.getPlayers().getHomeLocation(playerUUID, number);
}
// Check if it is safe
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Home location " + l);
}
if (l != null) {
if (isSafeLocation(l)) {
return l;
@ -456,38 +461,45 @@ public class IslandsManager {
}
}
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Home location either isn't safe, or does not exist so try the island");
}
// Home location either isn't safe, or does not exist so try the island
// location
if (plugin.getPlayers().inTeam(playerUUID)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG:player is in team");
}
l = plugin.getIslands().getIslandLocation(playerUUID);
if (isSafeLocation(l)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG:island loc is safe");
}
plugin.getPlayers().setHomeLocation(playerUUID, l, number);
return l;
} else {
// try team leader's home
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: trying leader's home");
}
Location tlh = plugin.getPlayers().getHomeLocation(plugin.getIslands().getTeamLeader(playerUUID));
if (tlh != null) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: leader has a home");
}
if (isSafeLocation(tlh)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: team leader's home is safe");
}
plugin.getPlayers().setHomeLocation(playerUUID, tlh, number);
return tlh;
}
}
}
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: player is not in team - trying island location");
}
l = plugin.getIslands().getIslandLocation(playerUUID);
if (isSafeLocation(l)) {
plugin.getPlayers().setHomeLocation(playerUUID, l, number);
@ -498,28 +510,32 @@ public class IslandsManager {
plugin.getLogger().warning(plugin.getPlayers().getName(playerUUID) + " player has no island!");
return null;
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: If these island locations are not safe, then we need to get creative");
}
// If these island locations are not safe, then we need to get creative
// Try the default location
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: try default location");
}
Location dl = new Location(l.getWorld(), l.getX() + 0.5D, l.getY() + 5D, l.getZ() + 2.5D, 0F, 30F);
if (isSafeLocation(dl)) {
plugin.getPlayers().setHomeLocation(playerUUID, dl, number);
return dl;
}
// Try just above the bedrock
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: above bedrock");
}
dl = new Location(l.getWorld(), l.getX() + 0.5D, l.getY() + 5D, l.getZ() + 0.5D, 0F, 30F);
if (isSafeLocation(dl)) {
plugin.getPlayers().setHomeLocation(playerUUID, dl, number);
return dl;
}
// Try all the way up to the sky
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: try all the way to the sky");
}
for (int y = l.getBlockY(); y < 255; y++) {
final Location n = new Location(l.getWorld(), l.getX() + 0.5D, y, l.getZ() + 0.5D);
if (isSafeLocation(n)) {
@ -527,8 +543,9 @@ public class IslandsManager {
return n;
}
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: unsuccessful");
}
// Unsuccessful
return null;
}
@ -542,8 +559,9 @@ public class IslandsManager {
*/
public Location getSpawnPoint() {
//plugin.getLogger().info("DEBUG: getting spawn point : " + spawn.getSpawnPoint());
if (spawn == null)
if (spawn == null) {
return null;
}
return spawn.getSpawnPoint();
}
@ -584,11 +602,13 @@ public class IslandsManager {
@SuppressWarnings("deprecation")
public void homeTeleport(final Player player, int number) {
Location home;
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("home teleport called for #" + number);
}
home = getSafeHomeLocation(player.getUniqueId(), number);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("home get safe loc = " + home);
}
// Check if the player is a passenger in a boat
if (player.isInsideVehicle()) {
Entity boat = player.getVehicle();
@ -601,14 +621,16 @@ public class IslandsManager {
}
}
if (home == null) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("Fixing home location using safe spot teleport");
}
// Try to fix this teleport location and teleport the player if possible
new SafeSpotTeleport(plugin, player, plugin.getPlayers().getHomeLocation(player.getUniqueId(), number), number);
return;
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: home loc = " + home + " teleporting");
}
//home.getChunk().load();
player.teleport(home);
//player.sendBlockChange(home, Material.GLOWSTONE, (byte)0);
@ -644,11 +666,13 @@ public class IslandsManager {
* @return
*/
public boolean isIsland(Location location){
if (location == null)
if (location == null) {
return true;
}
location = getClosestIsland(location);
if (islandCache.contains(location))
if (islandCache.contains(location)) {
return true;
}
if (!plugin.getSettings().isUseOwnGenerator()) {
// Block check
@ -708,18 +732,21 @@ public class IslandsManager {
islandCache.clear();
spawn = null;
try {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: loading grid");
}
for (Island island : handler.loadObjects()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding island at "+ island.getCenter());
}
islandCache.addIsland(island);
}
} catch (Exception e) {
plugin.getLogger().severe("Could not load islands to cache! " + e.getMessage());
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: islands loaded");
}
}
/**
@ -731,7 +758,7 @@ public class IslandsManager {
*/
public boolean locationIsAtHome(UUID uuid, boolean coop, Location loc) {
// Make a list of test locations and test them
Set<Location> islandTestLocations = new HashSet<Location>();
Set<Location> islandTestLocations = new HashSet<>();
if (plugin.getPlayers().hasIsland(uuid) || plugin.getPlayers().inTeam(uuid)) {
islandTestLocations.add(plugin.getIslands().getIslandLocation(uuid));
// If new Nether
@ -800,7 +827,7 @@ public class IslandsManager {
}
// Not in the grid, so do it the old way
// Make a list of test locations and test them
Set<Location> islandTestLocations = new HashSet<Location>();
Set<Location> islandTestLocations = new HashSet<>();
if (plugin.getPlayers().hasIsland(player.getUniqueId()) || plugin.getPlayers().inTeam(player.getUniqueId())) {
islandTestLocations.add(getIslandLocation(player.getUniqueId()));
}
@ -829,7 +856,7 @@ public class IslandsManager {
}
public void metrics_setCreatedCount(int count){
this.metrics_createdcount = count;
metrics_createdcount = count;
}
/**
@ -877,8 +904,9 @@ public class IslandsManager {
* @param playerUUID
*/
public void removePlayer(UUID playerUUID) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: removing player");
}
islandCache.removePlayer(playerUUID);
}
@ -925,8 +953,9 @@ public class IslandsManager {
Runnable save = () -> {
int index = 1;
for(Island island : collection){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving island async " + index++);
}
try {
handler.saveObject(island);
} catch (Exception e) {
@ -938,8 +967,9 @@ public class IslandsManager {
} else {
int index = 1;
for(Island island : collection){
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saving island " + index++);
}
try {
handler.saveObject(island);
} catch (Exception e) {
@ -967,8 +997,9 @@ public class IslandsManager {
*/
public boolean setJoinTeam(Island teamIsland, UUID playerUUID) {
// Add player to new island
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Adding player to new island");
}
teamIsland.addMember(playerUUID);
islandCache.addPlayer(playerUUID, teamIsland);
if (DEBUG) {
@ -990,8 +1021,9 @@ public class IslandsManager {
* @param playerUUID
*/
public void setLeaveTeam(UUID playerUUID) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: leaving team");
}
plugin.getPlayers().clearPlayerHomes(playerUUID);
removePlayer(playerUUID);
}

View File

@ -28,7 +28,7 @@ public class NewIsland {
private NewIsland(Island oldIsland, Player player, Reason reason) {
super();
this.plugin = BSkyBlock.getInstance();
plugin = BSkyBlock.getInstance();
this.player = player;
this.reason = reason;
newIsland();
@ -93,8 +93,9 @@ public class NewIsland {
* Makes an island.
*/
public void newIsland() {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: new island");
}
//long time = System.nanoTime();
final UUID playerUUID = player.getUniqueId();
/*
@ -102,11 +103,13 @@ public class NewIsland {
if (!plugin.getPlayers().hasIsland(playerUUID)) {
firstTime = true;
}*/
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: finding island location");
}
Location next = getNextIsland(player.getUniqueId());
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: found " + next);
}
// Add to the grid
island = plugin.getIslands().createIsland(next, playerUUID);
@ -123,16 +126,18 @@ public class NewIsland {
plugin.getPlayers().setHomeLocation(playerUUID, next, 1);
// Fire event
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: firing event");
}
IslandBaseEvent event = IslandEvent.builder()
.involvedPlayer(player.getUniqueId())
.reason(reason)
.island(island)
.location(island.getCenter())
.build();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: event cancelled status = " + event.isCancelled());
}
if (!event.isCancelled()) {
// Create island
new IslandBuilder(plugin, island)
@ -186,25 +191,30 @@ public class NewIsland {
Location last = plugin.getIslands().getLast();
if (DEBUG)
{
plugin.getLogger().info("DEBUG: last = " + last);
// Find the next free spot
// Find the next free spot
}
if (last == null) {
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)
if (DEBUG) {
plugin.getLogger().info("DEBUG: last 2 = " + last);
}
while (plugin.getIslands().isIsland(next)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: getting next loc");
}
next = nextGridLocation(next);
};
// Make the last next, last
last = next.clone();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: last 3 = " + last);
}
return next;
}

View File

@ -163,8 +163,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
//plugin.getLogger().info(setSql);
// Execute the statement
try (PreparedStatement collections = connection.prepareStatement(setSql)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collections prepared statement = " + collections.toString());
}
collections.executeUpdate();
}
}
@ -182,8 +183,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
//plugin.getLogger().info("DEBUG: SQL string = " + sql);
// Prepare and execute the database statements
pstmt = connection.prepareStatement(sql);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: pstmt = " + pstmt.toString());
}
pstmt.executeUpdate();
} catch (Exception e) {
plugin.getLogger().severe("Could not create database schema! " + e.getMessage());
@ -209,15 +211,17 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
boolean first = true;
/* Iterate the column-names */
for (Field f : dataObject.getDeclaredFields()) {
if (first)
if (first) {
first = false;
else
} else {
sb.append(", ");
}
if (usePlaceHolders)
if (usePlaceHolders) {
sb.append("?");
else
} else {
sb.append("`" + f.getName() + "`");
}
}
return sb.toString();
@ -240,18 +244,21 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
boolean first = true;
for (String col : cols) {
// Add commas
if (first)
if (first) {
first = false;
else
} else {
sb.append(", ");
}
// this is used if the string is going to be used to insert something so the value will replace the ?
if (usePlaceHolders)
if (usePlaceHolders) {
sb.append("?");
else
} else {
sb.append(col);
}
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection column string = " + sb.toString());
}
return sb.toString();
}
@ -269,8 +276,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
col += " " + en.getValue();
}
columns.add(col);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection columns = " + col);
}
}
return columns;
@ -288,11 +296,11 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// In this way, we can deduce what type needs to be written at runtime.
Type[] genericParameterTypes = method.getGenericParameterTypes();
// There could be more than one argument, so step through them
for (int i = 0; i < genericParameterTypes.length; i++) {
for (Type genericParameterType : genericParameterTypes) {
// If the argument is a parameter, then do something - this should always be true if the parameter is a collection
if (genericParameterTypes[i] instanceof ParameterizedType) {
if (genericParameterType instanceof ParameterizedType) {
// Get the actual type arguments of the parameter
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
Type[] parameters = ((ParameterizedType)genericParameterType).getActualTypeArguments();
//parameters[0] contains java.lang.String for method like "method(List<String> value)"
// Run through them one by one and create a SQL string
int index = 0;
@ -300,8 +308,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// This is a request for column names.
String setMapping = mySQLmapping.get(type.getTypeName());
columns.put("`" + type.getTypeName() + "_" + index + "`", setMapping != null ? setMapping : "VARCHAR(254)");
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection column = " + "`" + type.getTypeName() + "_" + index + "`" + setMapping);
}
}
// Increment the index so each column has a unique name
index++;
@ -381,8 +390,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Connection connection = null;
PreparedStatement preparedStatement = null;
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: saveObject ");
}
try {
// Try to connect to the database
connection = databaseConnecter.createConnection();
@ -400,37 +410,43 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
// Create the insertion
int i = 0;
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: insert Query " + insertQuery);
}
// Run through the fields in the class using introspection
for (Field field : dataObject.getDeclaredFields()) {
// Get the field's property descriptor
propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get the read method for this field
Method method = propertyDescriptor.getReadMethod();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Field = " + field.getName() + "(" + propertyDescriptor.getPropertyType().getTypeName() + ")");
}
//sql += "`" + field.getName() + "` " + mapping + ",";
// Invoke the read method to obtain the value from the class - this is the value we need to store in the database
Object value = method.invoke(instance);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: value = " + value);
}
// Adapter
// 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 (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: there is a configEntry");
}
}
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: there is an adapter");
}
// A conversion adapter has been defined
value = ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).deserialize(value);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: value now after deserialization = " + value);
}
}
// Create set and map table inserts if this is a Collection
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
@ -443,8 +459,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try (PreparedStatement collStatement = connection.prepareStatement(clearTableSql)) {
collStatement.setString(1, uniqueId);
collStatement.execute();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collStatement " + collStatement.toString());
}
}
// Insert into the table
String setSql = "INSERT INTO `" + dataObject.getCanonicalName() + "." + field.getName() + "` (uniqueId, ";
@ -456,8 +473,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try (PreparedStatement collStatement = connection.prepareStatement(setSql)) {
// Set the uniqueId
collStatement.setString(1, uniqueId);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection insert =" + setSql);
}
// Do single dimension types (set and list)
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
@ -474,8 +492,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
//}
// Set the value from ? to whatever it is
collStatement.setObject(2, setValue);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + collStatement.toString());
}
// Execute the SQL in the database
collStatement.execute();
}
@ -486,22 +505,26 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Iterator<?> it = collection.entrySet().iterator();
while (it.hasNext()) {
Entry<?,?> en = (Entry<?, ?>) it.next();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: entry ket = " + en.getKey());
}
// Get the key and serialize it
Object key = serialize(en.getKey(), en.getKey().getClass());
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: key class = " + en.getKey().getClass().getTypeName());
}
// Get the value and serialize it
Object mapValue = serialize(en.getValue(), en.getValue().getClass());
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: mapValue = " + mapValue);
}
// Write the objects into prepared statement
collStatement.setObject(1, key);
collStatement.setObject(2, mapValue);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + collStatement.toString());
}
// Write to database
collStatement.execute();
}
@ -521,8 +544,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Add the statements to a batch
preparedStatement.addBatch();
// Execute
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: prepared statement = " + preparedStatement.toString());
}
preparedStatement.executeBatch();
} finally {
@ -600,8 +624,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try {
connection = databaseConnecter.createConnection();
statement = connection.createStatement();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: selectQuery = " + selectQuery);
}
resultSet = statement.executeQuery(selectQuery);
return createObjects(resultSet);
@ -623,15 +648,17 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: loading object for " + uniqueId);
}
try {
connection = databaseConnecter.createConnection();
String query = "SELECT " + getColumns(false) + " FROM `" + dataObject.getCanonicalName() + "` WHERE uniqueId = ? LIMIT 1";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, uniqueId);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: load Object query = " + preparedStatement.toString());
}
resultSet = preparedStatement.executeQuery();
List<T> result = createObjects(resultSet);
@ -673,7 +700,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
IllegalAccessException, IntrospectionException,
InvocationTargetException, ClassNotFoundException {
List<T> list = new ArrayList<T>();
List<T> list = new ArrayList<>();
// The database can return multiple results in one go, e.g., all the islands in the database
// Run through them one by one
while (resultSet.next()) {
@ -693,14 +720,16 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// 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();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: propertyDescriptor.getPropertyType() = " + propertyDescriptor.getPropertyType());
}
// If the type is a Collection, then we need to deal with set and map tables
if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())
|| Map.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// Collection
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Collection or Map");
}
// TODO Get the values from the subsidiary tables.
// value is just of type boolean right now
String setSql = "SELECT ";
@ -713,21 +742,23 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try (PreparedStatement collStatement = connection.prepareStatement(setSql)) {
// Set the unique ID
collStatement.setObject(1, uniqueId);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: collStatement = " + collStatement.toString());
}
try (ResultSet collectionResultSet = collStatement.executeQuery()) {
//plugin.getLogger().info("DEBUG: collectionResultSet = " + collectionResultSet.toString());
// Do single dimension types (set and list)
if (Set.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding a set");
}
// Loop through the collection resultset
// Note that we have no idea what type this is
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
// collectionTypes should be only 1 long
Type setType = collectionTypes.get(0);
value = new HashSet<Object>();
value = new HashSet<>();
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
@ -736,14 +767,15 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
((Set<Object>) value).add(deserialize(collectionResultSet.getObject(1),Class.forName(setType.getTypeName())));
}
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Adding a list ");
}
// Loop through the collection resultset
// Note that we have no idea what type this is
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
// collectionTypes should be only 1 long
Type setType = collectionTypes.get(0);
value = new ArrayList<Object>();
value = new ArrayList<>();
//plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
while (collectionResultSet.next()) {
//plugin.getLogger().info("DEBUG: adding to the list");
@ -752,29 +784,34 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
} else if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType()) ||
HashMap.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Adding a map ");
}
// Loop through the collection resultset
// Note that we have no idea what type this is
List<Type> collectionTypes = Util.getCollectionParameterTypes(method);
// collectionTypes should be 2 long
Type keyType = collectionTypes.get(0);
Type valueType = collectionTypes.get(1);
value = new HashMap<Object, Object>();
if (DEBUG)
value = new HashMap<>();
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
}
while (collectionResultSet.next()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding to the map");
}
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
// Work through the columns
// Key
Object key = deserialize(collectionResultSet.getObject(1),Class.forName(keyType.getTypeName()));
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: key = " + key);
}
Object mapValue = deserialize(collectionResultSet.getObject(2),Class.forName(valueType.getTypeName()));
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: value = " + mapValue);
}
((Map<Object,Object>) value).put(key,mapValue);
}
} else {
@ -785,8 +822,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
}
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: regular type");
}
value = deserialize(value, propertyDescriptor.getPropertyType());
}
// Adapter
@ -795,17 +833,21 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// If there is a config annotation then do something
if (configEntry != null) {
if (DEBUG)
{
plugin.getLogger().info("DEBUG: there is a configEntry");
// TODO: add config entry handling
// TODO: add config entry handling
}
}
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: there is an adapter");
}
// A conversion adapter has been defined
value = ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).serialize(value);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: value now after deserialization = " + value);
}
}
if (DEBUG) {
plugin.getLogger().info("DEBUG: invoking method " + method.getName());
@ -833,8 +875,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object deserialize(Object value, Class<? extends Object> clazz) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getTypeName());
}
if (value instanceof String && value.equals("null")) {
// If the value is null as a string, return null
return null;
@ -894,8 +937,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: DELETE Query " + preparedStatement.toString());
}
preparedStatement.executeBatch();
// Delete from any sub tables created from the object
// Run through the fields in the class using introspection
@ -933,8 +977,9 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@Override
public boolean objectExits(String key) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: checking if " + key + " exists in the database");
}
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
@ -945,11 +990,13 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, key);
resultSet = preparedStatement.executeQuery();
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: object exists sql " + preparedStatement.toString());
}
if (resultSet.next()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: result is " + resultSet.getBoolean(1));
}
return resultSet.getBoolean(1);
}
} catch (SQLException e) {

View File

@ -17,8 +17,9 @@ public class MySQLDatabaseResourceCloser {
*/
public static void close(ResultSet... resultSets) {
if (resultSets == null)
if (resultSets == null) {
return;
}
for (ResultSet resultSet : resultSets) {
if (resultSet != null) {
@ -43,8 +44,9 @@ public class MySQLDatabaseResourceCloser {
* CallableStatement, because they extend Statement.
*/
if (statements == null)
if (statements == null) {
return;
}
for (Statement statement : statements) {
if (statement != null) {
@ -64,8 +66,9 @@ public class MySQLDatabaseResourceCloser {
* Connections that should be closed
*/
public static void close(Connection... connections) {
if (connections == null)
if (connections == null) {
return;
}
for (Connection connection : connections) {
if (connection != null) {

View File

@ -91,16 +91,16 @@ public class Island implements DataObject {
public Island(Location location, UUID owner, int protectionRange) {
setOwner(owner);
this.createdDate = System.currentTimeMillis();
this.updatedDate = System.currentTimeMillis();
this.world = location.getWorld();
this.center = location;
this.range = BSkyBlock.getInstance().getSettings().getIslandDistance();
this.minX = center.getBlockX() - range;
this.minZ = center.getBlockZ() - range;
createdDate = System.currentTimeMillis();
updatedDate = System.currentTimeMillis();
world = location.getWorld();
center = location;
range = BSkyBlock.getInstance().getSettings().getIslandDistance();
minX = center.getBlockX() - range;
minZ = center.getBlockZ() - range;
this.protectionRange = protectionRange;
this.minProtectedX = center.getBlockX() - protectionRange;
this.minProtectedZ = center.getBlockZ() - protectionRange;
minProtectedX = center.getBlockX() - protectionRange;
minProtectedZ = center.getBlockZ() - protectionRange;
}
/**
@ -108,8 +108,9 @@ public class Island implements DataObject {
* @param playerUUID
*/
public void addMember(UUID playerUUID) {
if (playerUUID != null)
if (playerUUID != null) {
members.put(playerUUID, RanksManager.MEMBER_RANK);
}
}
/**
@ -120,8 +121,9 @@ public class Island implements DataObject {
*/
public boolean addToBanList(UUID targetUUID) {
// TODO fire ban event
if (targetUUID != null)
if (targetUUID != null) {
members.put(targetUUID, RanksManager.BANNED_RANK);
}
return true;
}
@ -350,6 +352,7 @@ public class Island implements DataObject {
return result;
}
@Override
public String getUniqueId() {
// Island's have UUID's that are randomly assigned if they do not exist
if (uniqueId.isEmpty()) {
@ -418,7 +421,7 @@ public class Island implements DataObject {
* @return true if allowed, false if not
*/
public boolean isAllowed(Flag flag) {
return this.getFlag(flag) >= 0;
return getFlag(flag) >= 0;
}
/**
@ -429,7 +432,7 @@ public class Island implements DataObject {
*/
public boolean isAllowed(User user, Flag flag) {
//Bukkit.getLogger().info("DEBUG: " + flag.getID() + " user score = " + getRank(user) + " flag req = "+ this.getFlagReq(flag));
return this.getRank(user) >= this.getFlag(flag);
return getRank(user) >= getFlag(flag);
}
/**
@ -603,14 +606,16 @@ public class Island implements DataObject {
*/
public void setOwner(UUID owner){
this.owner = owner;
if (owner == null) return;
if (owner == null) {
return;
}
// Defensive code: demote any previous owner
for (Entry<UUID, Integer> en : members.entrySet()) {
if (en.getValue().equals(RanksManager.OWNER_RANK)) {
en.setValue(RanksManager.MEMBER_RANK);
}
}
this.members.put(owner, RanksManager.OWNER_RANK);
members.put(owner, RanksManager.OWNER_RANK);
}
/**
@ -640,21 +645,23 @@ public class Island implements DataObject {
* @param rank
*/
public void setRank(User user, int rank) {
if (user.getUniqueId() != null) members.put(user.getUniqueId(), rank);
if (user.getUniqueId() != null) {
members.put(user.getUniqueId(), rank);
}
}
/**
* @param ranks the ranks to set
*/
public void setRanks(HashMap<UUID, Integer> ranks) {
this.members = ranks;
members = ranks;
}
/**
* @param isSpawn - if the island is the spawn
*/
public void setSpawn(boolean isSpawn){
this.spawn = isSpawn;
spawn = isSpawn;
}
/**
@ -671,6 +678,7 @@ public class Island implements DataObject {
}
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}

View File

@ -38,14 +38,15 @@ public class Players implements DataObject {
*/
public Players(BSkyBlock plugin, final UUID uniqueId) {
this.uniqueId = uniqueId.toString();
this.homeLocations = new HashMap<>();
this.playerName = "";
this.resetsLeft = plugin.getSettings().getResetLimit();
this.locale = "";
this.kickedList = new HashMap<>();
this.playerName = Bukkit.getServer().getOfflinePlayer(uniqueId).getName();
if (this.playerName == null)
this.playerName = uniqueId.toString();
homeLocations = new HashMap<>();
playerName = "";
resetsLeft = plugin.getSettings().getResetLimit();
locale = "";
kickedList = new HashMap<>();
playerName = Bukkit.getServer().getOfflinePlayer(uniqueId).getName();
if (playerName == null) {
playerName = uniqueId.toString();
}
}
/**
@ -165,7 +166,7 @@ public class Players implements DataObject {
* @param uuid
*/
public void setPlayerUUID(final UUID uuid) {
this.uniqueId = uuid.toString();
uniqueId = uuid.toString();
}
/**
@ -210,9 +211,9 @@ public class Players implements DataObject {
* Add death
*/
public void addDeath() {
this.deaths++;
if (this.deaths > getPlugin().getSettings().getDeathsMax()) {
this.deaths = getPlugin().getSettings().getDeathsMax();
deaths++;
if (deaths > getPlugin().getSettings().getDeathsMax()) {
deaths = getPlugin().getSettings().getDeathsMax();
}
}

View File

@ -17,8 +17,8 @@ public interface AdapterInterface<S,V> {
*/
S serialize(Object object);
/**
* Deserialize object
/**
* Deserialize object
* @param object
* @return deserialized object
*/

View File

@ -21,8 +21,9 @@ public class FlagSerializer implements AdapterInterface<HashMap<Flag, Integer>,
@Override
public HashMap<Flag, Integer> serialize(Object object) {
HashMap<Flag, Integer> result = new HashMap<>();
if (object == null)
if (object == null) {
return result;
}
// For YAML
if (object instanceof MemorySection) {
MemorySection section = (MemorySection) object;
@ -42,8 +43,9 @@ public class FlagSerializer implements AdapterInterface<HashMap<Flag, Integer>,
@Override
public HashMap<String, Integer> deserialize(Object object) {
HashMap<String, Integer> result = new HashMap<>();
if (object == null)
if (object == null) {
return result;
}
HashMap<Flag, Integer> flags = (HashMap<Flag, Integer>)object;
for (Entry<Flag, Integer> en: flags.entrySet()) {
result.put(en.getKey().getID(), en.getValue());

View File

@ -22,13 +22,13 @@ public class PotionEffectListAdapter implements AdapterInterface<List<PotionEffe
@SuppressWarnings("unchecked")
@Override
public List<String> deserialize(Object to) {
List<String> result = new ArrayList<>();
if (to instanceof ArrayList) {
for (PotionEffectType type: (ArrayList<PotionEffectType>)to) {
result.add(type.getName());
}
}
return result;
List<String> result = new ArrayList<>();
if (to instanceof ArrayList) {
for (PotionEffectType type: (ArrayList<PotionEffectType>)to) {
result.add(type.getName());
}
}
return result;
}
}

View File

@ -32,17 +32,17 @@ public class NetherPopulator extends BlockPopulator {
if (b.getType().equals(Material.MOB_SPAWNER)) {
CreatureSpawner cs = (CreatureSpawner) b.getState();
switch (random.nextInt(3)) {
case 0:
cs.setSpawnedType(EntityType.BLAZE);
break;
case 1:
cs.setSpawnedType(EntityType.SKELETON);
break;
case 2:
cs.setSpawnedType(EntityType.MAGMA_CUBE);
break;
default:
cs.setSpawnedType(EntityType.BLAZE);
case 0:
cs.setSpawnedType(EntityType.BLAZE);
break;
case 1:
cs.setSpawnedType(EntityType.SKELETON);
break;
case 2:
cs.setSpawnedType(EntityType.MAGMA_CUBE);
break;
default:
cs.setSpawnedType(EntityType.BLAZE);
}
} else if (b.getType().equals(Material.OBSIDIAN)) {
b.setType(Material.CHEST);

View File

@ -50,7 +50,7 @@ public class IslandBuilder {
public IslandBuilder(BSkyBlock plugin, Island island) {
this.plugin = plugin;
this.island = island;
this.world = island.getWorld();
world = island.getWorld();
}
@ -61,16 +61,16 @@ public class IslandBuilder {
this.type = type;
switch(type) {
case END:
this.world = plugin.getIslandWorldManager().getEndWorld();
world = plugin.getIslandWorldManager().getEndWorld();
break;
case ISLAND:
this.world = plugin.getIslandWorldManager().getIslandWorld();
world = plugin.getIslandWorldManager().getIslandWorld();
break;
case NETHER:
this.world = plugin.getIslandWorldManager().getNetherWorld();
world = plugin.getIslandWorldManager().getNetherWorld();
break;
default:
this.world = island.getWorld();
world = island.getWorld();
break;
}
@ -82,8 +82,8 @@ public class IslandBuilder {
* @param player the player to set
*/
public IslandBuilder setPlayer(Player player) {
this.playerUUID = player.getUniqueId();
this.playerName = player.getName();
playerUUID = player.getUniqueId();
playerName = player.getName();
return this;
}
@ -92,7 +92,7 @@ public class IslandBuilder {
* @param list the default chestItems to set
*/
public IslandBuilder setChestItems(List<ItemStack> list) {
this.chestItems = list;
chestItems = list;
return this;
}
@ -477,7 +477,7 @@ public class IslandBuilder {
private void placeSign(int x, int y, int z) {
Block blockToChange = world.getBlockAt(x, y, z);
blockToChange.setType(Material.SIGN_POST);
if (this.playerUUID != null) {
if (playerUUID != null) {
Sign sign = (Sign) blockToChange.getState();
User user = User.getInstance(playerUUID);
for (int i = 0; i < 4; i++) {

View File

@ -25,7 +25,7 @@ public class JoinLeaveListener implements Listener {
*/
public JoinLeaveListener(BSkyBlock plugin) {
this.plugin = plugin;
this.players = plugin.getPlayers();
players = plugin.getPlayers();
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@ -39,48 +39,56 @@ public class JoinLeaveListener implements Listener {
}
UUID playerUUID = user.getUniqueId();
if (plugin.getPlayers().isKnown(playerUUID)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: known player");
}
// Load player
players.addPlayer(playerUUID);
// Reset resets if the admin changes it to or from unlimited
if (plugin.getSettings().getResetLimit() < players.getResetsLeft(playerUUID) || (plugin.getSettings().getResetLimit() >= 0 && players.getResetsLeft(playerUUID) < 0)) {
players.setResetsLeft(playerUUID, plugin.getSettings().getResetLimit());
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Setting player's name");
}
// Set the player's name (it may have changed), but only if it isn't empty
if (!user.getName().isEmpty()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Player name is " + user.getName());
}
players.setPlayerName(user);
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Saving player");
}
players.save(playerUUID);
} else {
plugin.getLogger().warning("Player that just logged in has no name! " + playerUUID.toString());
}
if (plugin.getSettings().isRemoveMobsOnLogin()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Removing mobs");
}
plugin.getIslands().removeMobs(user.getLocation());
}
// Check if they logged in to a locked island and expel them or if they are banned
Island currentIsland = plugin.getIslands().getIslandAt(user.getLocation()).orElse(null);
if (currentIsland != null && (currentIsland.isLocked() || plugin.getPlayers().isBanned(currentIsland.getOwner(),user.getUniqueId()))) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: Current island is locked, or player is banned");
}
if (!currentIsland.getMemberSet().contains(playerUUID) && !user.hasPermission(Constants.PERMPREFIX + "mod.bypassprotect")) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: No bypass - teleporting");
}
user.sendMessage("locked.islandlocked");
plugin.getIslands().homeTeleport(user.getPlayer());
}
}
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: not a known player");
}
}
}

View File

@ -55,12 +55,16 @@ public class PanelListenerManager implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClose(InventoryCloseEvent event) {
if (getOpenPanels().containsKey(event.getPlayer().getUniqueId())) getOpenPanels().remove(event.getPlayer().getUniqueId());
if (getOpenPanels().containsKey(event.getPlayer().getUniqueId())) {
getOpenPanels().remove(event.getPlayer().getUniqueId());
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onLogOut(PlayerQuitEvent event) {
if (getOpenPanels().containsKey(event.getPlayer().getUniqueId())) getOpenPanels().remove(event.getPlayer().getUniqueId());
if (getOpenPanels().containsKey(event.getPlayer().getUniqueId())) {
getOpenPanels().remove(event.getPlayer().getUniqueId());
}
}
/**

View File

@ -70,7 +70,9 @@ public abstract class AbstractFlagListener implements Listener {
* @param user
*/
public AbstractFlagListener setUser(User user) {
if (!plugin.getSettings().getFakePlayers().contains(user.getName())) this.user = user;
if (!plugin.getSettings().getFakePlayers().contains(user.getName())) {
this.user = user;
}
return this;
}
@ -92,11 +94,13 @@ public abstract class AbstractFlagListener implements Listener {
* @param silent - if true, message is not sent
*/
public void noGo(Event e, boolean silent) {
if (e instanceof Cancellable)
if (e instanceof Cancellable) {
((Cancellable)e).setCancelled(true);
}
if (user != null) {
if (!silent)
if (!silent) {
user.sendMessage("protection.protected");
}
user.updateInventory();
}
}
@ -152,7 +156,9 @@ public abstract class AbstractFlagListener implements Listener {
*/
public boolean checkIsland(Event e, Location loc, Flag flag, boolean silent) {
// If this is not an Island World, skip
if (!inWorld(loc)) return true;
if (!inWorld(loc)) {
return true;
}
// Get the island and if present
Optional<Island> island = getIslands().getIslandAt(loc);

View File

@ -52,7 +52,9 @@ public class BreakBlocksListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteract(final PlayerInteractEvent e) {
// Only handle hitting things
if (!e.getAction().equals(Action.LEFT_CLICK_BLOCK)) return;
if (!e.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
return;
}
// Look along player's sight line to see if any blocks are skulls
try {
@ -117,7 +119,9 @@ public class BreakBlocksListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamage(EntityDamageByEntityEvent e) {
// Only handle item frames and armor stands
if (!(e.getEntity() instanceof ItemFrame) && !(e.getEntity() instanceof ArmorStand)) return;
if (!(e.getEntity() instanceof ItemFrame) && !(e.getEntity() instanceof ArmorStand)) {
return;
}
// Get the attacker
if (e.getDamager() instanceof Player) {

View File

@ -41,13 +41,19 @@ public class BucketListener extends AbstractFlagListener {
public void onBucketFill(final PlayerBucketFillEvent e) {
// Check filling of various liquids
if (e.getItemStack().getType().equals(Material.LAVA_BUCKET)) {
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_LAVA)) return;
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_LAVA)) {
return;
}
}
if (e.getItemStack().getType().equals(Material.WATER_BUCKET)) {
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_WATER)) return;
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_WATER)) {
return;
}
}
if (e.getItemStack().getType().equals(Material.MILK_BUCKET)) {
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.MILKING)) return;
if (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.MILKING)) {
return;
}
}
// Check general bucket use
checkIsland(e, e.getBlockClicked().getLocation(), Flags.BUCKET);

View File

@ -42,10 +42,14 @@ public class FireListener extends AbstractFlagListener {
// Check if the island exists and if fire is allowed
Optional<Island> island = getIslands().getIslandAt(e.getBlock().getLocation());
island.ifPresent(x -> {
if (!x.isAllowed(Flags.FIRE_SPREAD)) e.setCancelled(true);
if (!x.isAllowed(Flags.FIRE_SPREAD)) {
e.setCancelled(true);
}
});
// If not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) e.setCancelled(true);
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) {
e.setCancelled(true);
}
}
/**
@ -61,10 +65,14 @@ public class FireListener extends AbstractFlagListener {
// Check if the island exists and if fire is allowed
Optional<Island> island = getIslands().getIslandAt(e.getBlock().getLocation());
island.ifPresent(x -> {
if (!x.isAllowed(Flags.FIRE_SPREAD)) e.setCancelled(true);
if (!x.isAllowed(Flags.FIRE_SPREAD)) {
e.setCancelled(true);
}
});
// If not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) e.setCancelled(true);
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) {
e.setCancelled(true);
}
}
}
@ -84,10 +92,14 @@ public class FireListener extends AbstractFlagListener {
// Check if the island exists and if fire is allowed
Optional<Island> island = getIslands().getIslandAt(e.getBlock().getLocation());
island.ifPresent(x -> {
if (!x.isAllowed(Flags.FIRE)) e.setCancelled(true);
if (!x.isAllowed(Flags.FIRE)) {
e.setCancelled(true);
}
});
// If not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) e.setCancelled(true);
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) {
e.setCancelled(true);
}
}
@ -137,13 +149,19 @@ public class FireListener extends AbstractFlagListener {
// Check if the island exists and if fire is allowed
Optional<Island> island = getIslands().getIslandAt(e.getBlock().getLocation());
island.ifPresent(x -> {
if (!x.isAllowed(Flags.FIRE)) e.setCancelled(true);
if (!x.isAllowed(Flags.FIRE)) {
e.setCancelled(true);
}
});
// If not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) e.setCancelled(true);
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) {
e.setCancelled(true);
}
// If either of these canceled the event, return
if (e.isCancelled()) return;
if (e.isCancelled()) {
return;
}
// Stop TNT from being damaged if it is being caused by a visitor with a flaming arrow
if (e.getEntity() instanceof Projectile) {

View File

@ -89,8 +89,9 @@ public class HurtingListener extends AbstractFlagListener {
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onFishing(PlayerFishEvent e) {
if (e.getCaught() == null)
if (e.getCaught() == null) {
return;
}
if ((e.getCaught() instanceof Animals || e.getCaught() instanceof IronGolem || e.getCaught() instanceof Snowman
|| e.getCaught() instanceof Villager) && checkIsland(e, e.getCaught().getLocation(), Flags.HURT_MONSTERS)) {
@ -126,7 +127,7 @@ public class HurtingListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onSplashPotionSplash(final PotionSplashEvent e) {
// Try to get the shooter
Projectile projectile = (Projectile) e.getEntity();
Projectile projectile = e.getEntity();
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
Player attacker = (Player)projectile.getShooter();
// Run through all the affected entities
@ -164,7 +165,7 @@ public class HurtingListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
// Try to get the shooter
Projectile projectile = (Projectile) e.getEntity();
Projectile projectile = e.getEntity();
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
UUID uuid = ((Player)projectile.getShooter()).getUniqueId();
// Store it and remove it when the effect is gone

View File

@ -45,8 +45,11 @@ public class PVPListener extends AbstractFlagListener {
public void onEntityDamage(final EntityDamageByEntityEvent e) {
if (e.getEntity() instanceof Player) {
Flag flag = Flags.PVP_OVERWORLD;
if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) flag = Flags.PVP_NETHER;
else if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) flag = Flags.PVP_END;
if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) {
flag = Flags.PVP_NETHER;
} else if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) {
flag = Flags.PVP_END;
}
respond(e, e.getDamager(), flag);
}
}
@ -73,8 +76,11 @@ public class PVPListener extends AbstractFlagListener {
public void onFishing(PlayerFishEvent e) {
if (e.getCaught() != null && e.getCaught() instanceof Player) {
Flag flag = Flags.PVP_OVERWORLD;
if (e.getCaught().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) flag = Flags.PVP_NETHER;
else if (e.getCaught().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) flag = Flags.PVP_END;
if (e.getCaught().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) {
flag = Flags.PVP_NETHER;
} else if (e.getCaught().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) {
flag = Flags.PVP_END;
}
if (checkIsland(e, e.getCaught().getLocation(), flag)) {
e.getHook().remove();
return;
@ -90,11 +96,14 @@ public class PVPListener extends AbstractFlagListener {
public void onSplashPotionSplash(final PotionSplashEvent e) {
// Deduce the world
Flag flag = Flags.PVP_OVERWORLD;
if (e.getPotion().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) flag = Flags.PVP_NETHER;
else if (e.getPotion().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) flag = Flags.PVP_END;
if (e.getPotion().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) {
flag = Flags.PVP_NETHER;
} else if (e.getPotion().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) {
flag = Flags.PVP_END;
}
// Try to get the thrower
Projectile projectile = (Projectile) e.getEntity();
Projectile projectile = e.getEntity();
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
Player attacker = (Player)projectile.getShooter();
// Run through all the affected entities
@ -118,7 +127,7 @@ public class PVPListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
// Try to get the shooter
Projectile projectile = (Projectile) e.getEntity();
Projectile projectile = e.getEntity();
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
UUID uuid = ((Player)projectile.getShooter()).getUniqueId();
// Store it and remove it when the effect is gone
@ -138,8 +147,11 @@ public class PVPListener extends AbstractFlagListener {
if (e.getCause().equals(DamageCause.ENTITY_ATTACK) && thrownPotions.containsKey(e.getDamager().getEntityId())) {
// Deduce the world
Flag flag = Flags.PVP_OVERWORLD;
if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) flag = Flags.PVP_NETHER;
else if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) flag = Flags.PVP_END;
if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getNetherWorld())) {
flag = Flags.PVP_NETHER;
} else if (e.getEntity().getWorld().equals(getPlugin().getIslandWorldManager().getEndWorld())) {
flag = Flags.PVP_END;
}
UUID attacker = thrownPotions.get(e.getDamager().getEntityId());
// Self damage

View File

@ -38,7 +38,7 @@ public class FlyingMobEvents implements Listener {
*/
public FlyingMobEvents(BSkyBlock plugin) {
this.plugin = plugin;
this.mobSpawnInfo = new WeakHashMap<>();
mobSpawnInfo = new WeakHashMap<>();
plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
//Bukkit.getLogger().info("DEBUG: checking - mobspawn size = " + mobSpawnInfo.size());

View File

@ -34,13 +34,13 @@ public final class AddonsManager {
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<?>>();
private final Map<String, Class<?>> classes = new HashMap<>();
private BSkyBlock plugin;
public AddonsManager(BSkyBlock plugin) {
this.plugin = plugin;
this.addons = new ArrayList<>();
this.loader = new ArrayList<>();
addons = new ArrayList<>();
loader = new ArrayList<>();
}
/**
@ -53,7 +53,7 @@ public final class AddonsManager {
for (File file : f.listFiles()) {
if (!file.isDirectory()) {
try {
this.loadAddon(file);
loadAddon(file);
} catch (InvalidAddonFormatException | InvalidAddonInheritException | InvalidDescriptionException e) {
plugin.getLogger().severe("Could not load addon " + file.getName() + " : " + e.getMessage());
}
@ -68,7 +68,7 @@ public final class AddonsManager {
}
}
this.addons.forEach(addon -> {
addons.forEach(addon -> {
addon.onEnable();
Bukkit.getPluginManager().callEvent(AddonEvent.builder().addon(addon).reason(AddonEvent.Reason.ENABLE).build());
addon.setEnabled(true);
@ -83,10 +83,14 @@ public final class AddonsManager {
* @return
*/
public Optional<Addon> getAddonByName(String name){
if(name.equals("")) return Optional.empty();
if(name.equals("")) {
return Optional.empty();
}
for(Addon addon : this.addons){
if(addon.getDescription().getName().contains(name)) return Optional.of(addon);
for(Addon addon : addons){
if(addon.getDescription().getName().contains(name)) {
return Optional.of(addon);
}
}
return Optional.empty();
}
@ -109,7 +113,7 @@ public final class AddonsManager {
// Open a reader to the jar
BufferedReader reader = new BufferedReader(new InputStreamReader(jar.getInputStream(entry)));
// Grab the description in the addon.yml file
Map<String, String> data = this.data(reader);
Map<String, String> data = data(reader);
// Load the addon
AddonClassLoader loader = new AddonClassLoader(this, data, f, this.getClass().getClassLoader());
@ -133,7 +137,7 @@ public final class AddonsManager {
Bukkit.getPluginManager().callEvent(AddonEvent.builder().addon(addon).reason(AddonEvent.Reason.LOAD).build());
// Add it to the list of addons
this.addons.add(addon);
addons.add(addon);
// Run the onLoad() method
addon.onLoad();
@ -153,8 +157,9 @@ public final class AddonsManager {
private Map<String, String> data(BufferedReader reader) {
Map<String, String> map = new HashMap<>();
reader.lines().forEach(string -> {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: " + string);
}
String[] data = string.split("\\: ");
if (data.length > 1) {
map.put(data[0], data[1].substring(0, data[1].length()));

View File

@ -13,9 +13,10 @@ public final class CommandsManager {
private HashMap<String, Command> commands = new HashMap<>();
public void registerCommand(Command command) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: registering command - " + command.getLabel());
commands.put(command.getLabel(), command);
}
commands.put(command.getLabel(), command);
// Use reflection to obtain the commandMap method in Bukkit's server. It used to be visible, but isn't anymore.
try{
Field commandMapField = Bukkit.getServer().getClass().getDeclaredField("commandMap");

View File

@ -66,7 +66,9 @@ public class FlagsManager {
public Flag getFlagByIcon(PanelItem item) {
for (Flag flag : flags.values()) {
if (flag.getIcon().equals(item)) return flag;
if (flag.getIcon().equals(item)) {
return flag;
}
}
return null;
}

View File

@ -24,7 +24,7 @@ public final class LocalesManager {
public LocalesManager(BSkyBlock plugin) {
this.plugin = plugin;
this.loadLocales("BSkyBlock"); // Default
loadLocales("BSkyBlock"); // Default
}
/**
@ -35,8 +35,9 @@ public final class LocalesManager {
*/
public String get(User user, String reference) {
BSBLocale locale = languages.get(user.getLocale());
if (locale != null && locale.contains(reference))
if (locale != null && locale.contains(reference)) {
return locale.get(reference);
}
// Return the default
if (languages.get(Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage())).contains(reference)) {
return languages.get(Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage())).get(reference);
@ -54,23 +55,22 @@ public final class LocalesManager {
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) {
// 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;
FilenameFilter ymlFilter = (dir, name) -> {
// 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 false;
return true;
}
return false;
};
// Run through the files and store the locales
File localeDir = new File(plugin.getDataFolder(), LOCALE_FOLDER + File.separator + parent);
if (DEBUG)
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()) {
@ -83,8 +83,9 @@ public final class LocalesManager {
// 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)
if (DEBUG) {
plugin.getLogger().info("DEBUG: targetFile = " + targetFile.getAbsolutePath());
}
if (!targetFile.exists()) {
java.nio.file.Files.copy(initialStream, targetFile.toPath());
}
@ -101,19 +102,23 @@ public final class LocalesManager {
// Store all the locales available
for (File language : localeDir.listFiles(ymlFilter)) {
if (DEBUG)
if (DEBUG) {
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)
if (DEBUG) {
plugin.getLogger().info("DEBUG: locale country found = " + localeObject.getCountry());
}
if (languages.containsKey(localeObject)) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: this locale is known");
}
// Merge into current language
languages.get(localeObject).merge(language);
} else {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: this locale is not known - new language");
}
// New language
languages.put(localeObject, new BSBLocale(localeObject, language));
}

View File

@ -67,9 +67,9 @@ public class RanksManager {
ranks.put(reference, value);
// Sort
ranks = ranks.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
return true;
}

View File

@ -27,11 +27,13 @@ public class DeleteIslandChunks {
//plugin.getLogger().info("DEBUG: deleting the island");
// Fire event
IslandBaseEvent event = IslandEvent.builder().island(island).reason(Reason.DELETE).build();
if (event.isCancelled())
if (event.isCancelled()) {
return;
}
final World world = island.getCenter().getWorld();
if (world == null)
if (world == null) {
return;
}
int minXChunk = island.getMinX() / 16;
int maxXChunk = (island.getRange() * 2 + island.getMinX() - 1) /16;
int minZChunk = island.getMinZ() / 16;

View File

@ -22,7 +22,7 @@ public class FileLister{
private Plugin plugin;
public FileLister(Plugin level){
this.plugin = level;
plugin = level;
}
/**
@ -52,7 +52,7 @@ public class FileLister{
Method method = JavaPlugin.class.getDeclaredMethod("getFile");
method.setAccessible(true);
jarfile = (File) method.invoke(this.plugin);
jarfile = (File) method.invoke(plugin);
} catch (Exception e) {
throw new IOException(e);
}
@ -97,7 +97,7 @@ public class FileLister{
Method method = JavaPlugin.class.getDeclaredMethod("getFile");
method.setAccessible(true);
jarfile = (File) method.invoke(this.plugin);
jarfile = (File) method.invoke(plugin);
} catch (Exception e) {
throw new IOException(e);
}

View File

@ -71,7 +71,7 @@ public class SafeSpotTeleport {
if (island != null) {
final World world = islandLoc.getWorld();
// Get the chunks
List<ChunkSnapshot> chunkSnapshot = new ArrayList<ChunkSnapshot>();
List<ChunkSnapshot> chunkSnapshot = new ArrayList<>();
// Add the center chunk
chunkSnapshot.add(island.getCenter().toVector().toLocation(world).getChunk().getChunkSnapshot());
// Add immediately adjacent chunks

View File

@ -110,11 +110,11 @@ public class Util {
// In this way, we can deduce what type needs to be written at runtime.
Type[] genericParameterTypes = writeMethod.getGenericParameterTypes();
// There could be more than one argument, so step through them
for (int i = 0; i < genericParameterTypes.length; i++) {
for (Type genericParameterType : genericParameterTypes) {
// If the argument is a parameter, then do something - this should always be true if the parameter is a collection
if( genericParameterTypes[i] instanceof ParameterizedType ) {
if( genericParameterType instanceof ParameterizedType ) {
// Get the actual type arguments of the parameter
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
Type[] parameters = ((ParameterizedType)genericParameterType).getActualTypeArguments();
result.addAll(Arrays.asList(parameters));
}
}
@ -128,17 +128,20 @@ public class Util {
*/
@SuppressWarnings("deprecation")
public static List<ItemStack> getPlayerInHandItems(Player player) {
List<ItemStack> result = new ArrayList<ItemStack>(2);
List<ItemStack> result = new ArrayList<>(2);
if (plugin.getServer().getVersion().contains("(MC: 1.7")
|| plugin.getServer().getVersion().contains("(MC: 1.8")) {
if (player.getItemInHand() != null)
if (player.getItemInHand() != null) {
result.add(player.getItemInHand());
}
return result;
}
if (player.getInventory().getItemInMainHand() != null)
if (player.getInventory().getItemInMainHand() != null) {
result.add(player.getInventory().getItemInMainHand());
if (player.getInventory().getItemInOffHand() != null)
}
if (player.getInventory().getItemInOffHand() != null) {
result.add(player.getInventory().getItemInOffHand());
}
return result;
}
@ -152,8 +155,9 @@ public class Util {
* Credits to mikenon on GitHub!
*/
public static String prettifyText(String ugly) {
if (!ugly.contains("_") && (!ugly.equals(ugly.toUpperCase())))
if (!ugly.contains("_") && (!ugly.equals(ugly.toUpperCase()))) {
return ugly;
}
String fin = "";
ugly = ugly.toLowerCase();
if (ugly.contains("_")) {
@ -162,8 +166,9 @@ public class Util {
for (String s : splt) {
i += 1;
fin += Character.toUpperCase(s.charAt(0)) + s.substring(1);
if (i < splt.length)
if (i < splt.length) {
fin += " ";
}
}
} else {
fin += Character.toUpperCase(ugly.charAt(0)) + ugly.substring(1);
@ -261,8 +266,9 @@ public class Util {
public static List<String> tabLimit(final List<String> list, final String start) {
final List<String> returned = new ArrayList<>();
for (String s : list) {
if (s == null)
if (s == null) {
continue;
}
if (s.toLowerCase().startsWith(start.toLowerCase())) {
returned.add(s);
}
@ -312,12 +318,7 @@ public class Util {
}
public static void runCommand(final Player player, final String string) {
plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
player.performCommand(string);
}});
plugin.getServer().getScheduler().runTask(plugin, () -> player.performCommand(string));
}

View File

@ -160,7 +160,7 @@ public class YmlCommentParser {
if (comment != null) {
sb.append((lineNum > 1 ? "\n" : "") + comment
.replaceAll("^#", Matcher.quoteReplacement(indent + "#"))
.replaceAll("\n#", Matcher.quoteReplacement("\n" + indent + "#")));
.replaceAll("\n#", Matcher.quoteReplacement("\n" + indent + "#")));
}
if (value != null && !value.trim().isEmpty()) {
// Scalar with value
@ -197,7 +197,7 @@ public class YmlCommentParser {
private Section(String name, int indentation) {
this.indentation = indentation;
this.path = name;
path = name;
}
public int getIndentation() {

View File

@ -82,7 +82,9 @@ public class PlaceholderHandler {
* @return updated message
*/
public static String replacePlaceholders(CommandSender receiver, String message){
if(message == null || message.isEmpty()) return "";
if(message == null || message.isEmpty()) {
return "";
}
for(PlaceholderInterface api : apis){
message = api.replacePlaceholders(receiver, message);

View File

@ -13,7 +13,7 @@ import us.tastybento.bskyblock.BSkyBlock;
* @author Poslovitch
*/
public class Placeholders {
private static Set<Placeholder> placeholders = new HashSet<Placeholder>();
private static Set<Placeholder> placeholders = new HashSet<>();
private BSkyBlock plugin;

View File

@ -33,7 +33,9 @@ public class InternalPlaceholderImpl implements PlaceholderInterface{
@Override
public String replacePlaceholders(CommandSender receiver, String message) {
if(message == null || message.isEmpty()) return "";
if(message == null || message.isEmpty()) {
return "";
}
for(Placeholder placeholder : Placeholders.getPlaceholders()){
String identifier = "{" + placeholder.getIdentifier() + "}";

View File

@ -38,6 +38,7 @@ import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
@ -126,7 +127,7 @@ public class TestBSkyBlock {
ItemFactory itemFactory = PowerMockito.mock(ItemFactory.class);
PowerMockito.when(Bukkit.getItemFactory()).thenReturn(itemFactory);
ItemMeta itemMeta = PowerMockito.mock(ItemMeta.class);
PowerMockito.when(itemFactory.getItemMeta(Mockito.any())).thenReturn(itemMeta);
PowerMockito.when(itemFactory.getItemMeta(Matchers.any())).thenReturn(itemMeta);
PowerMockito.mockStatic(Flags.class);
@ -162,7 +163,7 @@ public class TestBSkyBlock {
Bukkit.getLogger().info("SETUP: owner UUID = " + OWNER_UUID);
Bukkit.getLogger().info("SETUP: member UUID = " + MEMBER_UUID);
Bukkit.getLogger().info("SETUP: visitor UUID = " + VISITOR_UUID);
Mockito.when(im.getIslandAt(Mockito.any())).thenReturn(Optional.of(island));
Mockito.when(im.getIslandAt(Matchers.any())).thenReturn(Optional.of(island));
Settings settings = mock(Settings.class);
Mockito.when(plugin.getSettings()).thenReturn(settings);
@ -249,7 +250,7 @@ public class TestBSkyBlock {
public TestCommand() {
super(plugin, "test", "t", "tt");
this.setParameters("test.params");
setParameters("test.params");
}
@Override
@ -274,7 +275,7 @@ public class TestBSkyBlock {
@Override
public void setup() {
this.setParameters("sub.params");
setParameters("sub.params");
}
@Override
@ -335,7 +336,9 @@ public class TestBSkyBlock {
@Override
public boolean execute(User user, List<String> args) {
Bukkit.getLogger().info("args are " + args.toString());
if (args.size() == 3) return true;
if (args.size() == 3) {
return true;
}
return false;
}
@ -363,7 +366,7 @@ public class TestBSkyBlock {
return args.size() == 3 ? true : false;
}
}
}
// Protection tests
@Test