Implemented Ranks (#138), bug fixes and minor improvements

This commit is contained in:
Florian CUNY 2018-02-11 11:07:59 +01:00 committed by GitHub
commit f564af7f75
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
129 changed files with 6157 additions and 2682 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
/bin/
.classpath
.project
/.settings/
*.iml
/target
/.DS_Store

View File

@ -70,7 +70,9 @@ general:
mute-death-messages: false
# Allow FTB Autonomous Activator to work (will allow a pseudo player [CoFH] to place and break blocks and hang items)
allow-FTB-auto-activator: false
# Add other fake player names here if required
fakeplayers:
- "[CoFH]"
# Allow obsidian to be scooped up with an empty bucket back into lava
# This only works if there is a single block of obsidian (no obsidian within 10 blocks)
@ -273,6 +275,13 @@ island:
# Permission size cannot be less than the default below.
max-team-size: 4
# Ranks for players
# Pre-defined ranks are:
# Owner (1000), Member (700), Visitor (0) and Banned (-1)
# Rank names should be references to locale settings and must be in quotes
# like "ranks.coop".
"ranks.coop": 100
# Default maximum number of homes a player can have. Min = 1
# Accessed via sethome <number> or go <number>
# Use this permission to set for specific user groups: askyblock.island.maxhomes.<number>

View File

@ -81,10 +81,18 @@ commands:
description: "display detailed info about your team"
invite:
description: "invite a player to join your island"
invitation-sent: "Invitation sent to [name]"
removing-invite: "Removing invite"
name-has-invited-you: "[name] has invited you to join their island."
to-accept-or-reject: "Do /island team accept to accept, or /island team reject to reject"
you-will-lose-your-island: "&cWARNING! You will lose your island if you accept!"
errors:
cannot-invite-self: "&cYou cannot invite yourself!"
cooldown: "&cYou cannot invite that person for another [time] seconds"
island-is-full: "&cYour island is full, you can't invite anyone else."
none-invited-you: "&cNo one invited you :c."
you-already-are-in-team: "&cYou are already on a team!"
already-on-team: "&cThat player is already on a team!"
invalid-invite: "&cThat invite is no longer valid, sorry."
parameters: "<player>"
you-can-invite: "You can invite [number] more players."
@ -134,7 +142,15 @@ commands:
description: "select language"
parameters: "<language>"
ranks:
owner: "Owner"
member: "Member"
coop: "Coop"
visitor: "Visitor"
banned: "Banned"
protection:
protected: "&cIsland protected!"
flags:
ACID_DAMAGE: "Acid damage"
ANVIL: "Use anvil"

23
pom.xml
View File

@ -12,6 +12,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<powermock.version>1.7.1</powermock.version>
</properties>
<build>
<defaultGoal>clean package install</defaultGoal>
@ -63,6 +64,12 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
@ -70,16 +77,22 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.12.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots</url>
</repository>
</repositories>
</project>

View File

@ -3,6 +3,7 @@ package us.tastybento.bskyblock;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import us.tastybento.bskyblock.api.placeholders.PlaceholderHandler;
import us.tastybento.bskyblock.commands.AdminCommand;
import us.tastybento.bskyblock.commands.IslandCommand;
import us.tastybento.bskyblock.database.BSBDatabase;
@ -15,10 +16,11 @@ import us.tastybento.bskyblock.managers.AddonsManager;
import us.tastybento.bskyblock.managers.CommandsManager;
import us.tastybento.bskyblock.managers.FlagsManager;
import us.tastybento.bskyblock.managers.LocalesManager;
import us.tastybento.bskyblock.managers.RanksManager;
/**
* Main BSkyBlock class - provides an island minigame in the sky
* @author Tastybento
* @author tastybento
* @author Poslovitch
*/
public class BSkyBlock extends JavaPlugin {
@ -38,6 +40,7 @@ public class BSkyBlock extends JavaPlugin {
private AddonsManager addonsManager;
private FlagsManager flagsManager;
private IslandWorld islandWorldManager;
private RanksManager ranksManager;
// Settings
Settings settings;
@ -47,26 +50,27 @@ public class BSkyBlock extends JavaPlugin {
public void onEnable(){
// Save the default config from config.yml
saveDefaultConfig();
plugin = this;
setInstance(this);
settings = new Settings();
// Load settings from config.yml. This will check if there are any issues with it too.
// Load settings from config.yml. This will check if there are any issues with it too.
try {
//settings.saveSettings();
settings = settings.loadSettings();
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Settings could not be loaded" + e.getMessage());
}
// Save a backup of settings to the database so it can be checked next time
try {
settings.saveBackup();
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Settings backup could not be saved" + e.getMessage());
}
playersManager = new PlayersManager(this);
islandsManager = new IslandsManager(this);
ranksManager = new RanksManager(this);
// Load metrics
metrics = new Metrics(plugin);
@ -80,57 +84,35 @@ public class BSkyBlock extends JavaPlugin {
// These items have to be loaded when the server has done 1 tick.
// Note Worlds are not loaded this early, so any Locations or World reference will be null
// at this point. Therefore, the 1 tick scheduler is required.
getServer().getScheduler().runTask(this, new Runnable() {
getServer().getScheduler().runTask(this, () -> {
// Create the world if it does not exist
islandWorldManager = new IslandWorld(plugin);
@Override
public void run() {
// Create the world if it does not exist
islandWorldManager = new IslandWorld(plugin);
getServer().getScheduler().runTask(plugin, () -> {
getServer().getScheduler().runTask(plugin, new Runnable() {
// Load Flags
flagsManager = new FlagsManager(plugin);
@Override
public void run() {
// Load islands from database
islandsManager.load();
// Load islands from database
islandsManager.load();
localesManager = new LocalesManager(plugin);
//TODO localesManager.registerLocales(plugin);
localesManager = new LocalesManager(plugin);
PlaceholderHandler.register(plugin);
// Register Listeners
registerListeners();
// Register Listeners
registerListeners();
// Load Flags
flagsManager = new FlagsManager();
// Load addons
addonsManager = new AddonsManager(plugin);
addonsManager.enableAddons();
// Load addons
addonsManager = new AddonsManager(plugin);
addonsManager.enableAddons();
/*
*DEBUG CODE
Island loadedIsland = islandsManager.getIsland(owner);
getLogger().info("Island name = " + loadedIsland.getName());
getLogger().info("Island locked = " + loadedIsland.getLocked());
//getLogger().info("Random set = " + randomSet);
getLogger().info("Island coops = " + loadedIsland.getCoops());
for (Entry<SettingsFlag, Boolean> flag: loadedIsland.getFlags().entrySet()) {
getLogger().info("Flag " + flag.getKey().name() + " = " + flag.getValue());
}
*/
// Save islands & players data asynchronously every X minutes
getSettings().setDatabaseBackupPeriod(10 * 60 * 20);
plugin.getServer().getScheduler().runTaskTimer(plugin, new Runnable() {
@Override
public void run() {
playersManager.save(true);
islandsManager.save(true);
}
}, getSettings().getDatabaseBackupPeriod(), getSettings().getDatabaseBackupPeriod());
}
});
}
// Save islands & players data asynchronously every X minutes
getSettings().setDatabaseBackupPeriod(10 * 60 * 20);
plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
playersManager.save(true);
islandsManager.save(true);
}, getSettings().getDatabaseBackupPeriod(), getSettings().getDatabaseBackupPeriod());
});
});
}
@ -203,6 +185,10 @@ public class BSkyBlock extends JavaPlugin {
return islandsManager;
}
private static void setInstance(BSkyBlock plugin) {
BSkyBlock.plugin = plugin;
}
public static BSkyBlock getInstance() {
return plugin;
}
@ -250,4 +236,13 @@ public class BSkyBlock extends JavaPlugin {
return islandWorldManager;
}
/**
* @return the ranksManager
*/
public RanksManager getRanksManager() {
return ranksManager;
}
}

View File

@ -11,25 +11,24 @@ public class Constants {
BSKYBLOCK, ACIDISLAND, BOTH
}
/*
public final static GameType GAMETYPE = GameType.ACIDISLAND;
public static final GameType GAMETYPE = GameType.ACIDISLAND;
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
public static final String SPAWNCOMMAND = "spawn";
// Permission prefix
public final static String PERMPREFIX = "acidisland.";
public static final String PERMPREFIX = "acidisland.";
// The island command
public final static String ISLANDCOMMAND = "ai";
public static final String ISLANDCOMMAND = "ai";
// Admin command
public static final String ADMINCOMMAND = "acid";
*/
public final static GameType GAMETYPE = GameType.BSKYBLOCK;
*/
public static final GameType GAMETYPE = GameType.BSKYBLOCK;
// Permission prefix
public final static String PERMPREFIX = "bskyblock.";
public static final String PERMPREFIX = "bskyblock.";
// The island command
public final static String ISLANDCOMMAND = "island";
public static final String ISLANDCOMMAND = "island";
// The spawn command (Essentials spawn for example)
public final static String SPAWNCOMMAND = "spawn";
public static final String SPAWNCOMMAND = "spawn";
// Admin command
public static final String ADMINCOMMAND = "bsadmin";
}

View File

@ -30,7 +30,7 @@ import org.json.simple.JSONObject;
* bStats collects some data for plugin authors.
*
* Check out https://bStats.org/ to learn more about bStats!
*
*
* @author BtoBastian
*/
@SuppressWarnings("unchecked")
@ -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,14 +150,9 @@ 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*5, 1000*60*30);
}, 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
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
@ -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();
}
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");

View File

@ -2,8 +2,12 @@ package us.tastybento.bskyblock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
@ -12,10 +16,11 @@ import org.bukkit.potion.PotionEffectType;
import us.tastybento.bskyblock.Constants.GameType;
import us.tastybento.bskyblock.api.configuration.ConfigEntry;
import us.tastybento.bskyblock.api.configuration.ISettings;
import us.tastybento.bskyblock.api.configuration.PotionEffectListAdpater;
import us.tastybento.bskyblock.api.configuration.StoreAt;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.database.BSBDatabase.DatabaseType;
import us.tastybento.bskyblock.database.objects.adapters.Adapter;
import us.tastybento.bskyblock.database.objects.adapters.PotionEffectListAdapter;
/**
* All the plugin settings are here
@ -23,7 +28,9 @@ import us.tastybento.bskyblock.database.BSBDatabase.DatabaseType;
*/
@StoreAt(filename="config.yml") // Explicitly call out what name this should have.
public class Settings implements ISettings<Settings> {
private String uniqueId = "config";
// ---------------------------------------------
/* GENERAL */
@ -66,9 +73,8 @@ public class Settings implements ISettings<Settings> {
@ConfigEntry(path = "general.database.backup-period")
private int databaseBackupPeriod = 5;
//TODO change allowAutoActivator to the fakePlayers introduced in ASB 3.0.8
@ConfigEntry(path = "general.allow-FTB-auto-activators")
private boolean allowAutoActivator = false;
@ConfigEntry(path = "general.fakeplayers")
private Set<String> fakePlayers = new HashSet<>();
@ConfigEntry(path = "general.allow-obsidian-scooping")
private boolean allowObsidianScooping = true;
@ -127,37 +133,57 @@ public class Settings implements ISettings<Settings> {
private boolean endIslands = true;
// Entities
private HashMap<EntityType, Integer> entityLimits;
private HashMap<String, Integer> tileEntityLimits;
@ConfigEntry(path = "island.limits.entities")
private Map<EntityType, Integer> entityLimits = new EnumMap<>(EntityType.class);
@ConfigEntry(path = "island.limits.tile-entities")
private Map<String, Integer> tileEntityLimits = new HashMap<>();
// ---------------------------------------------
/* ISLAND */
private int maxTeamSize;
private int maxHomes;
private int nameMinLength;
private int nameMaxLength;
private int inviteWait;
@ConfigEntry(path = "island.max-team-size")
private int maxTeamSize = 4;
@ConfigEntry(path = "island.max-homes")
private int maxHomes = 5;
@ConfigEntry(path = "island.name.min-length")
private int nameMinLength = 4;
@ConfigEntry(path = "island.name.max-length")
private int nameMaxLength = 20;
@ConfigEntry(path = "island.invite-wait")
private int inviteWait = 60;
// Reset
private int resetLimit;
@ConfigEntry(path = "island.reset.reset-limit")
private int resetLimit = -1;
@ConfigEntry(path = "island.require-confirmation.reset")
private boolean resetConfirmation;
private boolean resetConfirmation = true;
@ConfigEntry(path = "island.require-confirmation.reset-wait")
private long resetWait;
@ConfigEntry(path = "island.reset-wait")
private long resetWait = 300;
private boolean leaversLoseReset;
private boolean kickedKeepInventory;
@ConfigEntry(path = "island.reset.leavers-lose-reset")
private boolean leaversLoseReset = false;
@ConfigEntry(path = "island.reset.kicked-keep-inventory")
private boolean kickedKeepInventory = false;
// Remove mobs
private boolean removeMobsOnLogin;
private boolean removeMobsOnIsland;
@ConfigEntry(path = "island.remove-mobs.on-login")
private boolean removeMobsOnLogin = false;
@ConfigEntry(path = "island.remove-mobs.on-island")
private boolean removeMobsOnIsland = false;
@ConfigEntry(path = "island.remove-mobs.whitelist")
private List<String> removeMobsWhitelist = new ArrayList<>();
private boolean makeIslandIfNone;
private boolean immediateTeleportOnIsland;
private boolean respawnOnIsland;
@ConfigEntry(path = "island.make-island-if-none")
private boolean makeIslandIfNone = false;
@ConfigEntry(path = "island.immediate-teleport-on-island")
private boolean immediateTeleportOnIsland = false;
private boolean respawnOnIsland = true;
// Deaths
@ConfigEntry(path = "island.deaths.max")
@ -166,6 +192,10 @@ public class Settings implements ISettings<Settings> {
@ConfigEntry(path = "island.deaths.sum-team")
private boolean deathsSumTeam = false;
// Ranks
@ConfigEntry(path = "island.customranks")
private Map<String, Integer> customRanks = new HashMap<>();
// ---------------------------------------------
/* PROTECTION */
@ -177,7 +207,7 @@ public class Settings implements ISettings<Settings> {
private int togglePvPCooldown;
private HashMap<Flag, Boolean> defaultFlags;
private Map<Flag, Boolean> defaultFlags = new HashMap<>();
//TODO transform these options below into flags
private boolean allowEndermanGriefing;
@ -214,37 +244,36 @@ public class Settings implements ISettings<Settings> {
@ConfigEntry(path = "acid.damage.rain", specificTo = GameType.ACIDISLAND)
private int acidRainDamage = 1;
@ConfigEntry(path = "acid.damage.effects", specificTo = GameType.ACIDISLAND, adapter = PotionEffectListAdpater.class)
@ConfigEntry(path = "acid.damage.effects", specificTo = GameType.ACIDISLAND)
@Adapter(PotionEffectListAdapter.class)
private List<PotionEffectType> acidEffects = new ArrayList<>(Arrays.asList(PotionEffectType.CONFUSION, PotionEffectType.SLOW));
/* SCHEMATICS */
private List<String> companionNames = new ArrayList<>();
@ConfigEntry(path = "island.chest-items")
private List<ItemStack> chestItems = new ArrayList<>();
private EntityType companionType = EntityType.COW;
private boolean useOwnGenerator;
private HashMap<String,Integer> limitedBlocks;
private Map<String,Integer> limitedBlocks = new HashMap<>();
private boolean teamJoinDeathReset;
private String uniqueId = "config";
// Timeout for team kick and leave commands
@ConfigEntry(path = "island.require-confirmation.kick")
private boolean kickConfirmation;
private boolean kickConfirmation = true;
@ConfigEntry(path = "island.require-confirmation.kick-wait")
private long kickWait;
private long kickWait = 300;
@ConfigEntry(path = "island.require-confirmation.leave")
private boolean leaveConfirmation;
private boolean leaveConfirmation = true;
@ConfigEntry(path = "island.require-confirmation.leave-wait")
private long leaveWait;
private long leaveWait = 300;
/**
* @return the acidDamage
@ -288,6 +317,12 @@ public class Settings implements ISettings<Settings> {
public EntityType getCompanionType() {
return companionType;
}
/**
* @return the customRanks
*/
public Map<String, Integer> getCustomRanks() {
return customRanks;
}
/**
* @return the databaseBackupPeriod
*/
@ -339,7 +374,7 @@ public class Settings implements ISettings<Settings> {
/**
* @return the defaultFlags
*/
public HashMap<Flag, Boolean> getDefaultFlags() {
public Map<Flag, Boolean> getDefaultFlags() {
return defaultFlags;
}
/**
@ -351,12 +386,11 @@ public class Settings implements ISettings<Settings> {
/**
* @return the entityLimits
*/
public HashMap<EntityType, Integer> getEntityLimits() {
public Map<EntityType, Integer> getEntityLimits() {
return entityLimits;
}
@Override
public Settings getInstance() {
// TODO Auto-generated method stub
return this;
}
/**
@ -422,7 +456,7 @@ public class Settings implements ISettings<Settings> {
/**
* @return the limitedBlocks
*/
public HashMap<String, Integer> getLimitedBlocks() {
public Map<String, Integer> getLimitedBlocks() {
return limitedBlocks;
}
/**
@ -494,7 +528,7 @@ public class Settings implements ISettings<Settings> {
/**
* @return the tileEntityLimits
*/
public HashMap<String, Integer> getTileEntityLimits() {
public Map<String, Integer> getTileEntityLimits() {
return tileEntityLimits;
}
/**
@ -506,6 +540,7 @@ public class Settings implements ISettings<Settings> {
/**
* @return the uniqueId
*/
@Override
public String getUniqueId() {
return uniqueId;
}
@ -527,12 +562,6 @@ public class Settings implements ISettings<Settings> {
public boolean isAcidDamageOp() {
return acidDamageOp;
}
/**
* @return the allowAutoActivator
*/
public boolean isAllowAutoActivator() {
return allowAutoActivator;
}
/**
* @return the allowChestDamage
*/
@ -761,12 +790,6 @@ public class Settings implements ISettings<Settings> {
public void setAcidRainDamage(int acidRainDamage) {
this.acidRainDamage = acidRainDamage;
}
/**
* @param allowAutoActivator the allowAutoActivator to set
*/
public void setAllowAutoActivator(boolean allowAutoActivator) {
this.allowAutoActivator = allowAutoActivator;
}
/**
* @param allowChestDamage the allowChestDamage to set
*/
@ -839,6 +862,12 @@ public class Settings implements ISettings<Settings> {
public void setCompanionType(EntityType companionType) {
this.companionType = companionType;
}
/**
* @param customRanks the customRanks to set
*/
public void setCustomRanks(Map<String, Integer> customRanks) {
this.customRanks = customRanks;
}
/**
* @param databaseBackupPeriod the databaseBackupPeriod to set
*/
@ -896,7 +925,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param defaultFlags the defaultFlags to set
*/
public void setDefaultFlags(HashMap<Flag, Boolean> defaultFlags) {
public void setDefaultFlags(Map<Flag, Boolean> defaultFlags) {
this.defaultFlags = defaultFlags;
}
/**
@ -926,7 +955,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param entityLimits the entityLimits to set
*/
public void setEntityLimits(HashMap<EntityType, Integer> entityLimits) {
public void setEntityLimits(Map<EntityType, Integer> entityLimits) {
this.entityLimits = entityLimits;
}
/**
@ -1022,7 +1051,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param limitedBlocks the limitedBlocks to set
*/
public void setLimitedBlocks(HashMap<String, Integer> limitedBlocks) {
public void setLimitedBlocks(Map<String, Integer> limitedBlocks) {
this.limitedBlocks = limitedBlocks;
}
/**
@ -1109,6 +1138,7 @@ public class Settings implements ISettings<Settings> {
public void setRemoveMobsOnIsland(boolean removeMobsOnIsland) {
this.removeMobsOnIsland = removeMobsOnIsland;
}
/**
* @param removeMobsOnLogin the removeMobsOnLogin to set
*/
@ -1121,7 +1151,6 @@ public class Settings implements ISettings<Settings> {
public void setRemoveMobsWhitelist(List<String> removeMobsWhitelist) {
this.removeMobsWhitelist = removeMobsWhitelist;
}
/**
* @param resetConfirmation the resetConfirmation to set
*/
@ -1167,7 +1196,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param tileEntityLimits the tileEntityLimits to set
*/
public void setTileEntityLimits(HashMap<String, Integer> tileEntityLimits) {
public void setTileEntityLimits(Map<String, Integer> tileEntityLimits) {
this.tileEntityLimits = tileEntityLimits;
}
/**
@ -1179,6 +1208,7 @@ public class Settings implements ISettings<Settings> {
/**
* @param uniqueId the uniqueId to set
*/
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
@ -1200,6 +1230,18 @@ public class Settings implements ISettings<Settings> {
public void setWorldName(String worldName) {
this.worldName = worldName;
}
/**
* @return the fakePlayers
*/
public Set<String> getFakePlayers() {
return fakePlayers;
}
/**
* @param fakePlayers the fakePlayers to set
*/
public void setFakePlayers(Set<String> fakePlayers) {
this.fakePlayers = fakePlayers;
}
}

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,29 +90,31 @@ public abstract class Addon implements AddonInterface {
/**
* Load a YAML file
*
* @param file
* @return Yaml File configuration
*/
private FileConfiguration loadYamlFile(String file) {
File yamlFile = new File(dataFolder, file);
YamlConfiguration config = null;
YamlConfiguration yamlConfig = null;
if (yamlFile.exists()) {
try {
config = new YamlConfiguration();
config.load(yamlFile);
yamlConfig = new YamlConfiguration();
yamlConfig.load(yamlFile);
} catch (Exception e) {
e.printStackTrace();
Bukkit.getLogger().severe("Could not load YAML file: " + file);
}
}
return config;
return yamlConfig;
}
/**
* 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) {
e.printStackTrace();
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("")) {
@ -157,65 +170,67 @@ public abstract class Addon implements AddonInterface {
}
jarResource = jarResource.replace('\\', '/');
InputStream in = null;
try {
JarFile jar = new JarFile(file);
JarEntry config = jar.getJarEntry(jarResource);
if (config != null) {
in = jar.getInputStream(config);
try (JarFile jar = new JarFile(file)) {
JarEntry jarConfig = jar.getJarEntry(jarResource);
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());
}
// There are two options, use the path of the resource or not
File outFile = new File(destinationFolder, jarResource);
if (noPath) {
outFile = new File(destinationFolder, outFile.getName());
}
// Make any dirs that need to be made
outFile.getParentFile().mkdirs();
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: outFile = " + outFile.getAbsolutePath());
Bukkit.getLogger().info("DEBUG: outFile name = " + outFile.getName());
}
if (!outFile.exists() || replace) {
java.nio.file.Files.copy(in, outFile.toPath());
}
}
}
if (in == null) {
jar.close();
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);
if (noPath) {
outFile = new File(destinationFolder, outFile.getName());
}
// Make any dirs that need to be made
outFile.getParentFile().mkdirs();
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: outFile = " + outFile.getAbsolutePath());
Bukkit.getLogger().info("DEBUG: outFile name = " + outFile.getName());
}
if (!outFile.exists() || replace) {
java.nio.file.Files.copy(in, outFile.toPath());
}
in.close();
jar.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (IOException e) {
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

@ -1,6 +1,5 @@
package us.tastybento.bskyblock.api.addons;
import java.io.BufferedReader;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
@ -8,6 +7,7 @@ import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.plugin.InvalidDescriptionException;
import us.tastybento.bskyblock.BSkyBlock;
@ -21,60 +21,57 @@ import us.tastybento.bskyblock.managers.AddonsManager;
*/
public class AddonClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
public 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, BufferedReader reader, ClassLoader parent) throws InvalidAddonInheritException, MalformedURLException, InvalidAddonFormatException, InvalidDescriptionException {
super(new URL[]{path.toURI().toURL()}, parent);
this.loader = addonsManager;
Addon addon = null;
Class<?> javaClass = null;
try {
//Bukkit.getLogger().info("data " + data.get("main"));
/*
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);
loader = addonsManager;
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");
}
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'");
}
try {
addon = addonClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
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'");
}
addon = addonClass.newInstance();
addon.setDescription(asDescription(data));
}
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();
}
addon.setDescription(this.asDescription(data));
this.addon = addon;
}
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();
}
/* (non-Javadoc)
* @see java.net.URLClassLoader#findClass(java.lang.String)
*/
@ -85,35 +82,42 @@ public class AddonClassLoader extends URLClassLoader {
/**
* This is a custom findClass that enables classes in other addons to be found
* (This code was copied from Bukkit's PluginLoader class
* @param name
* @param checkGlobal
* @return Class
* @throws ClassNotFoundException
*/
public Class<?> findClass(String name, boolean checkGlobal) throws ClassNotFoundException {
if (name.startsWith("us.tastybento.")) {
throw new ClassNotFoundException(name);
}
Class<?> result = classes.get(name);
return classes.computeIfAbsent(name, k -> createFor(k, checkGlobal));
}
if (result == null) {
if (checkGlobal) {
result = loader.getClassByName(name);
}
if (result == null) {
result = super.findClass(name);
if (result != null) {
loader.setClass(name, result);
}
}
classes.put(name, result);
private Class<?> createFor(String name, boolean checkGlobal) {
Class<?> result = null;
if (checkGlobal) {
result = loader.getClassByName(name);
}
if (result == null) {
try {
result = super.findClass(name);
} catch (ClassNotFoundException e) {
Bukkit.getLogger().severe("Could not find class! " + e.getMessage());
}
if (result != null) {
loader.setClass(name, result);
}
}
return result;
}
/**
* @return the addon
*/
public Addon getAddon() {
return addon;
}
}

View File

@ -15,7 +15,7 @@ public final class AddonDescription {
private List<String> authors;
public AddonDescription() {}
public AddonDescription(String main, String name, String version, String description, List<String> authors) {
this.main = main;
this.name = name;
@ -78,34 +78,34 @@ public final class AddonDescription {
public List<String> getAuthors() {
return authors;
}
public static class AddonDescriptionBuilder{
public AddonDescription description;
private AddonDescription description;
public AddonDescriptionBuilder(String name){
description = new AddonDescription();
description.setName(name);
}
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();
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");
}
@Override
public void printStackTrace(){
super.printStackTrace();
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");
}
}

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,16 +71,16 @@ 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,24 +93,25 @@ 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)
}
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: registering command " + label);
}
}
/**
@ -120,33 +121,35 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
*/
public CompositeCommand(String label, String... aliases) {
super(label);
if (DEBUG)
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);
}
}
/*
* This method deals with the command execution. It traverses the tree of
/*
* This method deals with the command execution. It traverses the tree of
* subcommands until it finds the right object and then runs execute on it.
*/
@Override
public boolean execute(CommandSender sender, String label, String[] args) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: executing command " + label);
}
// Get the User instance for this sender
User user = User.getInstance(sender);
CompositeCommand cmd = getCommandFromArgs(args);
@ -173,7 +176,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
if (event.isCancelled()) {
return true;
}
// Execute and trim args
return cmd.execute(user, Arrays.asList(args).subList(cmd.subCommandLevel, args.length));
}
@ -186,34 +189,22 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
private CompositeCommand getCommandFromArgs(String[] args) {
CompositeCommand subCommand = this;
// Run through any arguments
if (DEBUG)
Bukkit.getLogger().info("DEBUG: Running through args: " + Arrays.asList(args).toString());
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (DEBUG)
Bukkit.getLogger().info("DEBUG: Argument " + i);
// get the subcommand corresponding to the arg
if (subCommand.hasSubCommmands()) {
if (DEBUG)
Bukkit.getLogger().info("DEBUG: This command has subcommands");
if (subCommand.hasSubCommand(args[i])) {
// Step down one
subCommand = subCommand.getSubCommand(args[i]).get();
if (DEBUG)
Bukkit.getLogger().info("DEBUG: Moved to " + subCommand.getLabel());
// Set the label
subCommand.setLabel(args[i]);
} else {
return subCommand;
}
} else {
// We are at the end of the walk
if (DEBUG)
Bukkit.getLogger().info("DEBUG: End of traversal");
for (String arg : args) {
// get the subcommand corresponding to the arg
if (subCommand.hasSubCommmands()) {
Optional<CompositeCommand> sub = subCommand.getSubCommand(arg);
if (!sub.isPresent()) {
return subCommand;
}
// else continue the loop
// Step down one
subCommand = sub.orElse(subCommand);
// Set the label
subCommand.setLabel(arg);
} else {
// We are at the end of the walk
return subCommand;
}
// else continue the loop
}
return subCommand;
}
@ -263,7 +254,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
@Override
public String getPermission() {
return this.permission;
return permission;
}
/**
@ -294,18 +285,25 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
* @return CompositeCommand or null if none found
*/
public Optional<CompositeCommand> getSubCommand(String label) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: label = " + label);
}
for (Map.Entry<String, CompositeCommand> entry : subCommands.entrySet()) {
if (DEBUG)
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)
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();
}
@ -337,7 +335,7 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
* @param subCommand
* @return true if this command has this sub command
*/
private boolean hasSubCommand(String subCommand) {
protected boolean hasSubCommand(String subCommand) {
return subCommands.containsKey(subCommand) || subCommandAliases.containsKey(subCommand);
}
@ -402,11 +400,11 @@ 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;
while (parent != null) {
this.usage = parent.getLabel() + " " + this.usage;
parent = parent.getParent();
CompositeCommand parentCommand = getParent();
this.usage = getLabel() + " " + usage;
while (parentCommand != null) {
this.usage = parentCommand.getLabel() + " " + this.usage;
parentCommand = parentCommand.getParent();
}
this.usage = this.usage.trim();
return this;
@ -422,17 +420,19 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
}
// Check for console and permissions
if (cmd.onlyPlayer && !(sender instanceof Player)) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: returning, only for player");
}
return options;
}
if (!cmd.getPermission().isEmpty() && !sender.hasPermission(cmd.getPermission())) {
if (DEBUG)
if (DEBUG) {
Bukkit.getLogger().info("DEBUG: failed perm check");
}
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
@ -464,4 +464,17 @@ public abstract class CompositeCommand extends Command implements PluginIdentifi
}
return Util.tabLimit(options, lastArg);
}
/**
* Show help
* @param command
* @param user
* @param args
*/
protected void showHelp(CompositeCommand command, User user, List<String> args) {
Optional<CompositeCommand> helpCommand = command.getSubCommand("help");
if (helpCommand.isPresent()) {
helpCommand.get().execute(user, args);
}
}
}

View File

@ -16,6 +16,10 @@ public class DefaultHelpCommand extends CompositeCommand {
// TODO: make this a setting
private static final int MAX_DEPTH = 2;
private static final String USAGE_PLACEHOLDER = "[usage]";
private static final String PARAMS_PLACEHOLDER = "[parameters]";
private static final String DESC_PLACEHOLDER = "[description]";
private static final String HELP_SYNTAX_REF = "commands.help.syntax";
public DefaultHelpCommand(CompositeCommand parent) {
super(parent, "help");
@ -24,8 +28,9 @@ 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());
setPermission(parent.getPermission());
}
@Override
@ -39,7 +44,7 @@ public class DefaultHelpCommand extends CompositeCommand {
String usage = user.getTranslation(parent.getUsage());
String params = user.getTranslation("commands.help.parameters");
String desc = user.getTranslation("commands.help.description");
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
return true;
}
}
@ -57,14 +62,14 @@ public class DefaultHelpCommand extends CompositeCommand {
if (user.isPlayer()) {
// Player. Check perms
if (user.hasPermission(parent.getPermission())) {
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
} else {
// No permission, nothing to see here. If you don't have permission, you cannot see any sub commands
return true;
}
} else if (!parent.isOnlyPlayer()) {
// Console. Only show if it is a console command
user.sendMessage("commands.help.syntax", "[usage]", usage, "[parameters]", params, "[description]", desc);
user.sendMessage(HELP_SYNTAX_REF, USAGE_PLACEHOLDER, usage, PARAMS_PLACEHOLDER, params, DESC_PLACEHOLDER, desc);
}
}
// Increment the depth
@ -74,14 +79,14 @@ public class DefaultHelpCommand extends CompositeCommand {
// Ignore the help command
if (!subCommand.getLabel().equals("help")) {
// Every command should have help because every command has a default help
if (subCommand.getSubCommand("help").isPresent()) {
// This sub-sub command has a help, so use it
subCommand.getSubCommand("help").get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
Optional<CompositeCommand> sub = subCommand.getSubCommand("help");
if (sub.isPresent()) {
sub.get().execute(user, Arrays.asList(String.valueOf(newDepth)));
}
}
}
}
if (depth == 0) {
user.sendMessage("commands.help.end");
}

View File

@ -17,6 +17,7 @@ import org.bukkit.inventory.PlayerInventory;
import org.bukkit.permissions.PermissionAttachmentInfo;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.placeholders.PlaceholderHandler;
/**
* BSB's user object. Wraps Player.
@ -44,8 +45,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 +82,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 +162,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) {
@ -168,7 +172,10 @@ public class User {
translation = translation.replace(variables[i], variables[i+1]);
}
}
// Replace placeholders
translation = PlaceholderHandler.replacePlaceholders(this, translation);
return ChatColor.translateAlternateColorCodes('&', translation);
}
@ -182,7 +189,7 @@ public class User {
String translation = getTranslation(reference, variables);
return translation.equals(reference) ? "" : translation;
}
/**
* Send a message to sender if message is not empty. Does not include color codes or spaces.
* @param reference - language file reference
@ -199,7 +206,7 @@ public class User {
}
}
}
/**
* Sends a message to sender without any modification (colors, multi-lines, placeholders).
* Should only be used for debug purposes.
@ -244,17 +251,22 @@ public class User {
public void closeInventory() {
player.closeInventory();
}
/**
* Get the user's locale
* @return Locale
*/
public Locale getLocale() {
if (sender instanceof Player) {
if (!plugin.getPlayers().getLocale(this.playerUUID).isEmpty())
return Locale.forLanguageTag(plugin.getPlayers().getLocale(this.playerUUID));
}
if (sender instanceof Player && !plugin.getPlayers().getLocale(playerUUID).isEmpty()) {
return Locale.forLanguageTag(plugin.getPlayers().getLocale(playerUUID));
}
return Locale.forLanguageTag(plugin.getSettings().getDefaultLanguage());
}
@SuppressWarnings("deprecation")
public void updateInventory() {
player.updateInventory();
}
}

View File

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

View File

@ -22,6 +22,5 @@ public @interface ConfigEntry {
boolean experimental() default false;
boolean needsReset() default false;
GameType specificTo() default GameType.BOTH;
Class<?> adapter() default Adapter.class;
}

View File

@ -14,13 +14,14 @@ import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
* Simple interface for tagging all classes containing ConfigEntries.
*
* @author Poslovitch
* @author tastybento
* @param <T>
*/
public interface ISettings<T> {
// ----------------Saver-------------------
@SuppressWarnings("unchecked")
default void saveSettings() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
default void saveSettings() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
// Get the handler
AbstractDatabaseHandler<T> settingsHandler = (AbstractDatabaseHandler<T>) new FlatFileDatabase().getHandler(getInstance().getClass());
// Load every field in the config class
@ -29,20 +30,20 @@ public interface ISettings<T> {
settingsHandler.saveSettings(getInstance());
}
default void saveBackup() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
// Save backup in real database
default void saveBackup() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IntrospectionException, SQLException {
// Save backup
@SuppressWarnings("unchecked")
AbstractDatabaseHandler<T> dbhandler = (AbstractDatabaseHandler<T>) BSBDatabase.getDatabase().getHandler(getInstance().getClass());
dbhandler.saveObject(getInstance());
AbstractDatabaseHandler<T> backupHandler = (AbstractDatabaseHandler<T>) new FlatFileDatabase().getHandler(getInstance().getClass());
backupHandler.saveObject(getInstance());
}
// --------------- Loader ------------------
@SuppressWarnings("unchecked")
default T loadSettings() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, ClassNotFoundException, IntrospectionException, SQLException {
default T loadSettings() throws InstantiationException, IllegalAccessException, InvocationTargetException, 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())) {
if (dbhandler.objectExists(this.getUniqueId())) {
// Load it
dbConfig = dbhandler.loadObject(getUniqueId());
}

View File

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

View File

@ -23,11 +23,11 @@ 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();
}
/**
* @param island
* @param playerUUID
@ -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

@ -6,7 +6,7 @@ import org.bukkit.event.HandlerList;
public abstract class PremadeEvent extends Event {
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;

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

@ -20,7 +20,7 @@ public class CommandEvent extends PremadeEvent implements Cancellable {
private final Command command;
private final String label;
private final String[] args;
private CommandEvent(CommandSender sender, Command command, String label, String[] args) {
super();
this.sender = sender;
@ -32,14 +32,14 @@ public class CommandEvent extends PremadeEvent implements Cancellable {
public static CommandEventBuilder builder() {
return new CommandEventBuilder();
}
public static class CommandEventBuilder {
// Here field are NOT final. They are just used for the building.
private CommandSender sender;
private Command command;
private String label;
private String[] args;
public CommandEventBuilder setSender(CommandSender sender) {
this.sender = sender;
return this;
@ -63,7 +63,7 @@ public class CommandEvent extends PremadeEvent implements Cancellable {
public CommandEvent build() {
return new CommandEvent(sender, command, label, args);
}
}
public CommandSender getSender() {
@ -89,6 +89,6 @@ public class CommandEvent extends PremadeEvent implements Cancellable {
@Override
public void setCancelled(boolean arg0) {
cancelled = arg0;
cancelled = arg0;
}
}

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

@ -2,7 +2,6 @@ package us.tastybento.bskyblock.api.events.island;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import us.tastybento.bskyblock.BSkyBlock;
@ -144,10 +143,10 @@ public class IslandEvent {
}
public IslandEventBuilder location(Location center) {
this.location = center;
location = center;
return this;
}
public IslandBaseEvent build() {
switch (reason) {
case CREATE:
@ -195,7 +194,7 @@ public class IslandEvent {
BSkyBlock.getInstance().getServer().getPluginManager().callEvent(general);
return general;
}
}
}
}

View File

@ -24,7 +24,7 @@ public class PurgeStartEvent extends PremadeEvent implements Cancellable {
/**
* Called to create the event
* @param user - the UUID of the player who launched the purge, may be null if purge is launched using the console.
* @param islandsList - the list of islands to remove, based on their leader's UUID
* @param islandsList - the list of islands to remove, based on their leader's UUID
*/
public PurgeStartEvent(UUID user, List<UUID> islandsList) {
this.user = user;
@ -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
* @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,10 +134,10 @@ public class TeamEvent {
}
public TeamEventBuilder location(Location center) {
this.location = center;
location = center;
return this;
}
public IslandBaseEvent build() {
switch (reason) {
case JOIN:

View File

@ -4,20 +4,26 @@ import java.util.Optional;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.panels.PanelItem;
public class Flag {
public class Flag implements Comparable<Flag> {
private String id;
private PanelItem icon;
private Optional<Listener> listener;
public enum FlagType {
PROTECTION,
SETTING
}
public Flag(String id, PanelItem icon, Optional<Listener> listener) {
this.id = id;
private final String id;
private final PanelItem icon;
private final Listener listener;
private final FlagType type;
private boolean defaultSetting;
public Flag(String id2, PanelItem icon, Listener listener, boolean defaultSetting, FlagType type) {
id = id2;
this.icon = icon;
this.listener = listener;
BSkyBlock.getInstance().getFlagsManager().registerFlag(this);
this.type = type;
}
public String getID() {
@ -29,6 +35,26 @@ public class Flag {
}
public Optional<Listener> getListener() {
return listener;
return Optional.ofNullable(listener);
}
public boolean isDefaultSetting() {
return defaultSetting;
}
public void setDefaultSetting(boolean defaultSetting) {
this.defaultSetting = defaultSetting;
}
/**
* @return the type
*/
public FlagType getType() {
return type;
}
@Override
public int compareTo(Flag o) {
return id.compareTo(o.getID());
}
}

View File

@ -1,22 +1,23 @@
package us.tastybento.bskyblock.api.flags;
import java.util.Optional;
import org.bukkit.Material;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import us.tastybento.bskyblock.api.flags.Flag.FlagType;
import us.tastybento.bskyblock.api.panels.PanelItem;
import us.tastybento.bskyblock.api.panels.builders.PanelItemBuilder;
public class FlagBuilder {
private String id = "";
private PanelItem icon = PanelItem.empty();
private Optional<Listener> listener = Optional.empty();
private String id;
private PanelItem icon;
private Listener listener;
private boolean defaultSetting;
private FlagType type = FlagType.PROTECTION;
public FlagBuilder id(String id) {
this.id = id;
public FlagBuilder id(String string) {
id = string;
return this;
}
@ -34,11 +35,41 @@ public class FlagBuilder {
}
public FlagBuilder listener(Listener listener) {
this.listener = Optional.of(listener);
this.listener = listener;
return this;
}
public Flag build() {
return new Flag(id, icon, listener);
return new Flag(id, icon, listener, defaultSetting, type);
}
/**
* Sets the default setting for this flag in the world
* @param setting
* @return
*/
public FlagBuilder allowedByDefault(boolean setting) {
defaultSetting = setting;
return this;
}
/**
* Set the type of this flag
* @param type {@link FlagType}
* @return FlagBuilder
*/
public FlagBuilder type(FlagType type) {
this.type = type;
return this;
}
/**
* Set the id of this flag to the name of this enum value
* @param flag
* @return
*/
public FlagBuilder id(Enum<?> flag) {
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

@ -22,7 +22,7 @@ public class Panel {
// If size is undefined (0) then use the number of items
if (size == 0) {
size = items.keySet().size();
}
}
// Create panel
if (size > 0) {
// Make sure size is a multiple of 9
@ -70,7 +70,7 @@ public class Panel {
public void open(Player... players) {
for (Player player : players) {
player.openInventory(inventory);
PanelListenerManager.openPanels.put(player.getUniqueId(), this);
PanelListenerManager.getOpenPanels().put(player.getUniqueId(), this);
}
}
@ -81,7 +81,7 @@ public class Panel {
public void open(User... users) {
for (User user : users) {
user.getPlayer().openInventory(inventory);
PanelListenerManager.openPanels.put(user.getUniqueId(), this);
PanelListenerManager.getOpenPanels().put(user.getUniqueId(), this);
}
}

View File

@ -3,7 +3,6 @@ package us.tastybento.bskyblock.api.panels;
import java.util.List;
import java.util.Optional;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
@ -19,23 +18,23 @@ public class PanelItem {
}
private ItemStack icon;
private Optional<ClickHandler> clickHandler;
private ClickHandler clickHandler;
private List<String> description;
private String name;
private boolean glow;
private ItemMeta meta;
public PanelItem(ItemStack icon, String name, List<String> description, boolean glow, Optional<ClickHandler> clickHandler) {
public PanelItem(ItemStack icon, String name, List<String> description, boolean glow, ClickHandler clickHandler) {
this.icon = icon;
// Get the meta
meta = icon.getItemMeta();
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);
@ -70,7 +69,7 @@ public class PanelItem {
}
public Optional<ClickHandler> getClickHandler() {
return clickHandler;
return Optional.of(clickHandler);
}
public boolean isGlow() {
@ -79,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

@ -11,7 +11,7 @@ public interface PanelListener {
* This is called when the panel is first setup
*/
void setup();
/**
* Called when the panel is clicked
* @param user

View File

@ -27,27 +27,27 @@ 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;
}
}
}
/**
* Checks if a slot is occupied in the panel or not
* @param slot to check
* @return true or false
*/
public boolean slotOccupied(int slot) {
return this.items.containsKey(slot);
return items.containsKey(slot);
}
/**
* Build the panel
* @return Panel
@ -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

@ -3,8 +3,8 @@ package us.tastybento.bskyblock.api.panels.builders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
@ -16,7 +16,7 @@ public class PanelItemBuilder {
private String name = "";
private List<String> description = new ArrayList<>();
private boolean glow = false;
private Optional<PanelItem.ClickHandler> clickHandler = Optional.empty();
private PanelItem.ClickHandler clickHandler;
public PanelItemBuilder icon(Material icon) {
this.icon = new ItemStack(icon);
@ -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) {
@ -47,18 +47,21 @@ public class PanelItemBuilder {
this.description.add(description);
return this;
}
public PanelItemBuilder glow(boolean glow) {
this.glow = glow;
return this;
}
public PanelItemBuilder clickHandler(ClickHandler clickHandler) {
this.clickHandler = Optional.of(clickHandler);
this.clickHandler = clickHandler;
return this;
}
public PanelItem build() {
if (icon == null) {
Bukkit.getLogger().info("DEBUG: icon is null");
}
return new PanelItem(icon, name, description, glow, clickHandler);
}

View File

@ -0,0 +1,29 @@
package us.tastybento.bskyblock.api.placeholders;
import us.tastybento.bskyblock.api.commands.User;
/**
* @author Poslovitch
*/
public class Placeholder {
private String identifier;
private PlaceholderRequest request;
Placeholder(String identifier, PlaceholderRequest request) {
this.identifier = identifier;
this.request = request;
}
public String getIdentifier() {
return this.identifier;
}
public PlaceholderRequest getRequest() {
return request;
}
public interface PlaceholderRequest {
String request(User user);
}
}

View File

@ -1,40 +1,39 @@
package us.tastybento.bskyblock.util.placeholders;
import org.bukkit.command.CommandSender;
package us.tastybento.bskyblock.api.placeholders;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
/**
* Simple interface for every Placeholder API.
*
*
* @author Poslovitch
*/
public interface PlaceholderInterface {
public interface PlaceholderAPIInterface {
/**
* Get the name of the Placeholder API
* Gets the name of the Placeholder API
* @return name of the placeholder plugin
*/
String getName();
/**
* Register the placeholder API
* Registers the placeholder API
* @param plugin
* @return true if registered
* @return true if successfully registered
*/
boolean register(BSkyBlock plugin);
/**
* Unregister the placeholder API
* Unregisters the placeholder API
* @param plugin
*/
void unregister(BSkyBlock plugin);
/**
* Replace placeholders in the message according to the receiver
* @param sender
* @param receiver
* @param message
* @return updated message
*/
String replacePlaceholders(CommandSender receiver, String message);
String replacePlaceholders(User receiver, String message);
}

View File

@ -0,0 +1,21 @@
package us.tastybento.bskyblock.api.placeholders;
public class PlaceholderBuilder {
private String identifier;
private Placeholder.PlaceholderRequest value;
public PlaceholderBuilder identifier(String identifier) {
this.identifier = identifier;
return this;
}
public PlaceholderBuilder value(Placeholder.PlaceholderRequest value) {
this.value = value;
return this;
}
public Placeholder build() {
return new Placeholder(identifier, value);
}
}

View File

@ -1,20 +1,23 @@
package us.tastybento.bskyblock.util.placeholders;
package us.tastybento.bskyblock.api.placeholders;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bukkit.command.CommandSender;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
/**
* Handles hooks with other Placeholder APIs.
*
*
* @author Poslovitch, Tastybento
*/
public class PlaceholderHandler {
private static final String PACKAGE = "us.tastybento.bskyblock.util.placeholders.hooks.";
private static final String PACKAGE = "us.tastybento.bskyblock.api.placeholders.hooks.";
// This class should never be instantiated (all methods are static)
private PlaceholderHandler() {}
/**
* List of API classes in the package specified above (except the Internal one)
*/
@ -22,25 +25,22 @@ public class PlaceholderHandler {
//TODO
};
private static List<PlaceholderInterface> apis = new ArrayList<>();
private static List<PlaceholderAPIInterface> apis = new ArrayList<>();
/**
* Register placeholders and hooks
* @param plugin
*/
public static void register(BSkyBlock plugin){
// Register placeholders
new Placeholders(plugin);
// Load Internal Placeholder API
try{
Class<?> clazz = Class.forName(PACKAGE + "InternalPlaceholderImpl");
PlaceholderInterface internal = (PlaceholderInterface)clazz.newInstance();
PlaceholderAPIInterface internal = (PlaceholderAPIInterface)clazz.newInstance();
apis.add(internal);
} catch (Exception e){
// Should never happen.
plugin.getLogger().severe("Failed to load default placeholder API");
e.printStackTrace();
}
// Load hooks
@ -48,16 +48,15 @@ public class PlaceholderHandler {
if(plugin.getServer().getPluginManager().isPluginEnabled(hook)){
try{
Class<?> clazz = Class.forName(PACKAGE + hook + "PlaceholderImpl");
PlaceholderInterface api = (PlaceholderInterface)clazz.newInstance();
PlaceholderAPIInterface api = (PlaceholderAPIInterface)clazz.newInstance();
if(api.register(plugin)){
plugin.getLogger().info("Hooked placeholders into " + hook);
plugin.getLogger().info(() -> "Hooked placeholders into " + hook); // since Java 8, we can use Supplier , which will be evaluated lazily
apis.add(api);
} else {
plugin.getLogger().info("Failed to hook placeholders into " + hook);
plugin.getLogger().info(() -> "Failed to hook placeholders into " + hook);
}
} catch (Exception e){
plugin.getLogger().info("Failed to hook placeholders into " + hook);
e.printStackTrace();
plugin.getLogger().info(() -> "Failed to hook placeholders into " + hook);
}
}
}
@ -68,9 +67,9 @@ public class PlaceholderHandler {
* @param plugin
*/
public static void unregister(BSkyBlock plugin){
Iterator<PlaceholderInterface> it = apis.iterator();
Iterator<PlaceholderAPIInterface> it = apis.iterator();
while (it.hasNext()) {
PlaceholderInterface api = it.next();
PlaceholderAPIInterface api = it.next();
api.unregister(plugin);
it.remove();
}
@ -82,10 +81,8 @@ public class PlaceholderHandler {
* @param message
* @return updated message
*/
public static String replacePlaceholders(CommandSender receiver, String message){
if(message == null || message.isEmpty()) return "";
for(PlaceholderInterface api : apis){
public static String replacePlaceholders(User receiver, String message){
for(PlaceholderAPIInterface api : apis){
message = api.replacePlaceholders(receiver, message);
}
@ -96,6 +93,6 @@ public class PlaceholderHandler {
* @return true if APIs are registered (including Internal), otherwise false
*/
public static boolean hasHooks(){
return apis != null ? true : false;
return apis != null;
}
}

View File

@ -0,0 +1,45 @@
package us.tastybento.bskyblock.api.placeholders.hooks;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.placeholders.Placeholder;
import us.tastybento.bskyblock.api.placeholders.PlaceholderAPIInterface;
import us.tastybento.bskyblock.lists.Placeholders;
/**
* Built-in placeholder API
*
* @author Poslovitch
*/
public class InternalPlaceholderImpl implements PlaceholderAPIInterface {
@Override
public String getName() {
return "Internal";
}
@Override
public boolean register(BSkyBlock plugin) {
return true;
}
@Override
public void unregister(BSkyBlock plugin) {
// Useless : it would disable the placeholders.
}
@Override
public String replacePlaceholders(User receiver, String message) {
if(message == null || message.isEmpty()) {
return "";
}
for(Placeholder placeholder : Placeholders.values()){
String identifier = "%" + placeholder.getIdentifier() + "%";
message = message.replaceAll(identifier, placeholder.getRequest().request(receiver));
}
return message;
}
}

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("commands.admin.help.description");
new AdminVersionCommand(this);
new AdminReloadCommand(this);
new AdminTeleportCommand(this);
@ -27,7 +27,9 @@ public class AdminCommand extends CompositeCommand {
@Override
public boolean execute(User user, List<String> args) {
return this.getSubCommand("help").get().execute(user, args);
// By default run the attached help command, if it exists (it should)
showHelp(this, user, args);
return false;
}
}

View File

@ -1,6 +1,8 @@
package us.tastybento.bskyblock.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
@ -25,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);
@ -43,11 +45,22 @@ public class IslandCommand extends CompositeCommand {
@Override
public boolean execute(User user, List<String> args) {
// If this player does not have an island, create one
if (!getPlugin().getIslands().hasIsland(user.getUniqueId())) {
return this.getSubCommand("create").get().execute(user, args);
Optional<CompositeCommand> subCreate = getSubCommand("create");
if (subCreate.isPresent()) {
subCreate.get().execute(user, new ArrayList<>());
}
return true;
}
// Currently, just go home
return this.getSubCommand("go").get().execute(user, args);
Optional<CompositeCommand> go = getSubCommand("go");
// Otherwise, currently, just go home
if (go.isPresent()) {
go.get().execute(user, new ArrayList<>());
}
return true;
}
}

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package us.tastybento.bskyblock.commands.admin;
@ -9,18 +9,16 @@ import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
/**
* @author ben
* @author tastybento
*
*/
public class AdminReloadCommand extends CompositeCommand {
/**
* @param parent
* @param label
* @param aliases
*/
public AdminReloadCommand(CompositeCommand parent) {
super(parent, "reload");
super(parent, "reload", "rl");
}
/* (non-Javadoc)
@ -28,8 +26,7 @@ public class AdminReloadCommand extends CompositeCommand {
*/
@Override
public void setup() {
// TODO Auto-generated method stub
setDescription("commands.admin.reload.description");
}
/* (non-Javadoc)

View File

@ -8,7 +8,7 @@ import org.bukkit.Location;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.CompositeCommand;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.util.SafeSpotTeleport;
import us.tastybento.bskyblock.util.SafeTeleportBuilder;
public class AdminTeleportCommand extends CompositeCommand {
@ -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
@ -29,28 +29,31 @@ public class AdminTeleportCommand extends CompositeCommand {
user.sendMessage("commands.admin.tp.help");
return true;
}
// Convert name to a UUID
final UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("errors.unknown-player");
return true;
return false;
} else {
if (getPlayers().hasIsland(targetUUID) || getPlayers().inTeam(targetUUID)) {
Location warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getIslandWorld());
if (this.getLabel().equals("tpnether")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getNetherWorld());
} else if (this.getLabel().equals("tpend")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getEndWorld());
if (getLabel().equals("tpnether")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getNetherWorld());
} else if (getLabel().equals("tpend")) {
warpSpot = getIslands().getIslandLocation(targetUUID).toVector().toLocation(getPlugin().getIslandWorldManager().getEndWorld());
}
// Other wise, go to a safe spot
String failureMessage = user.getTranslation("commands.admin.tp.manual", "[location]", warpSpot.getBlockX() + " " + warpSpot.getBlockY() + " "
+ warpSpot.getBlockZ());
new SafeSpotTeleport(getPlugin(), user.getPlayer(), warpSpot, failureMessage);
new SafeTeleportBuilder(getPlugin()).entity(user.getPlayer())
.location(warpSpot)
.failureMessage(failureMessage)
.build();
return true;
}
user.sendMessage("command.admin.tp.no-island");
return true;
return false;
}
}

View File

@ -9,13 +9,14 @@ import us.tastybento.bskyblock.api.commands.User;
public class AdminVersionCommand extends CompositeCommand {
public AdminVersionCommand(CompositeCommand adminCommand) {
super(adminCommand, "version");
super(adminCommand, "version", "v");
}
@Override
public void setup() {
// Permission
this.setPermission(Constants.PERMPREFIX + "admin.version");
setPermission(Constants.PERMPREFIX + "admin.version");
setDescription("commands.admin.version.description");
}
@Override

View File

@ -11,25 +11,25 @@ import us.tastybento.bskyblock.util.Util;
* This is a custom help for the /island go and /island sethome commands. It overrides the default help sub command.
* The number of homes can change depending on the player's permissions and config.yml settings.
* This is an example of a custom help as much as anything.
*
*
* @author tastybento
*
*/
public class CustomIslandMultiHomeHelp extends CompositeCommand {
public CustomIslandMultiHomeHelp(CompositeCommand parent) {
super(parent, "help");
super(parent, "help");
}
@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
public boolean execute(User user, List<String> args) {
// This will only be shown if it is for a player
@ -56,6 +56,6 @@ public class CustomIslandMultiHomeHelp extends CompositeCommand {
}
return false;
}
}

View File

@ -15,12 +15,12 @@ public class IslandAboutCommand extends CompositeCommand {
public IslandAboutCommand(CompositeCommand islandCommand) {
super(islandCommand, "about", "ab");
}
@Override
public void setup() {
this.setDescription("commands.island.about.description");
setDescription("commands.island.about.description");
}
@Override
public boolean execute(User user, List<String> args) {
user.sendRawMessage("About " + BSkyBlock.getInstance().getDescription().getName() + " v" + BSkyBlock.getInstance().getDescription().getVersion() + ":");

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package us.tastybento.bskyblock.commands.island;
@ -23,12 +23,12 @@ public class IslandCreateCommand extends CompositeCommand {
public IslandCreateCommand(IslandCommand islandCommand) {
super(islandCommand, "create", "auto");
}
@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)
@ -41,7 +41,7 @@ public class IslandCreateCommand extends CompositeCommand {
return false;
}
if (getPlayers().inTeam(user.getUniqueId())) {
return false;
return false;
}
user.sendMessage("commands.island.create.creating-island");
createIsland(user);
@ -60,9 +60,8 @@ public class IslandCreateCommand extends CompositeCommand {
.reason(Reason.CREATE)
.build();
} catch (IOException e) {
getPlugin().getLogger().severe("Could not create island for player.");
getPlugin().getLogger().severe("Could not create island for player. " + e.getMessage());
user.sendMessage("commands.island.create.unable-create-island");
e.printStackTrace();
}
}
}

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package us.tastybento.bskyblock.commands.island;
@ -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);
}
@ -39,7 +39,7 @@ public class IslandGoCommand extends CompositeCommand {
public boolean execute(User user, List<String> args) {
if (!getIslands().hasIsland(user.getUniqueId())) {
user.sendMessage(ChatColor.RED + "general.errors.no-island");
return true;
return false;
}
if (!args.isEmpty() && NumberUtils.isDigits(args.get(0))) {
int homeValue = Integer.valueOf(args.get(0));

View File

@ -20,12 +20,12 @@ public class IslandResetCommand extends CompositeCommand {
public IslandResetCommand(CompositeCommand islandCommand) {
super(islandCommand, "reset", "restart");
}
@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
@ -36,7 +36,7 @@ public class IslandResetCommand extends CompositeCommand {
}
if (!getIslands().isOwner(user.getUniqueId())) {
user.sendMessage("general.errors.not-leader");
return false;
return false;
}
if (getPlugin().getPlayers().inTeam(user.getUniqueId())) {
user.sendMessage("commands.island.reset.must-remove-members");
@ -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)
@ -62,9 +65,8 @@ public class IslandResetCommand extends CompositeCommand {
.oldIsland(oldIsland)
.build();
} catch (IOException e) {
getPlugin().getLogger().severe("Could not create island for player.");
getPlugin().getLogger().severe("Could not create island for player. " + e.getMessage());
user.sendMessage("commands.island.create.unable-create-island");
e.printStackTrace();
}
return true;
}

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package us.tastybento.bskyblock.commands.island;
@ -19,12 +19,12 @@ public class IslandResetnameCommand extends CompositeCommand {
public IslandResetnameCommand(CompositeCommand islandCommand) {
super(islandCommand, "resetname");
}
@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");
}
@ -37,12 +37,12 @@ public class IslandResetnameCommand extends CompositeCommand {
if (!getIslands().hasIsland(playerUUID)) {
user.sendMessage("general.errors.no-island");
return true;
return false;
}
if (!getIslands().isOwner(playerUUID)) {
user.sendMessage("general.errors.not-leader");
return true;
return false;
}
// Resets the island name
getIslands().getIsland(playerUUID).setName(null);

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);
}
@ -28,11 +28,11 @@ public class IslandSethomeCommand extends CompositeCommand {
// Check island
if (getPlugin().getIslands().getIsland(user.getUniqueId()) == null) {
user.sendMessage("general.errors.no-island");
return true;
return false;
}
if (!getPlugin().getIslands().playerIsOnIsland(user)) {
user.sendMessage("commands.island.sethome.must-be-on-your-island");
return true;
return false;
}
if (args.isEmpty()) {
// island sethome
@ -48,15 +48,18 @@ public class IslandSethomeCommand extends CompositeCommand {
number = Integer.valueOf(args.get(0));
if (number < 1 || number > maxHomes) {
user.sendMessage("commands.island.sethome.num-homes", "[max]", String.valueOf(maxHomes));
return false;
} else {
getPlugin().getPlayers().setHomeLocation(playerUUID, user.getLocation(), number);
user.sendMessage("commands.island.sethome.home-set");
}
} catch (Exception e) {
user.sendMessage("commands.island.sethome.num-homes", "[max]", String.valueOf(maxHomes));
return false;
}
} else {
user.sendMessage("general.errors.no-permission");
return false;
}
}
return true;

View File

@ -1,5 +1,5 @@
/**
*
*
*/
package us.tastybento.bskyblock.commands.island;
@ -23,13 +23,13 @@ public class IslandSetnameCommand extends CompositeCommand {
public IslandSetnameCommand(CompositeCommand islandCommand) {
super(islandCommand, "setname");
}
@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)
@ -42,17 +42,17 @@ public class IslandSetnameCommand extends CompositeCommand {
if (!getIslands().hasIsland(playerUUID)) {
user.sendMessage("general.errors.no-island");
return true;
return false;
}
if (!getIslands().isOwner(playerUUID)) {
user.sendMessage("general.errors.not-leader");
return true;
return false;
}
// Explain command
if (args.isEmpty()) {
user.sendMessage(getUsage());
return true;
showHelp(this, user, args);
return false;
}
// Naming the island - join all the arguments with spaces.
@ -61,17 +61,19 @@ public class IslandSetnameCommand extends CompositeCommand {
// Check if the name isn't too short or too long
if (name.length() < getSettings().getNameMinLength()) {
user.sendMessage("commands.island.setname.too-short", "[length]", String.valueOf(getSettings().getNameMinLength()));
return true;
return false;
}
if (name.length() > getSettings().getNameMaxLength()) {
user.sendMessage("commands.island.setname.too-long", "[length]", String.valueOf(getSettings().getNameMaxLength()));
return true;
return false;
}
// 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

@ -20,21 +20,21 @@ import us.tastybento.bskyblock.api.commands.User;
*
*/
public abstract class AbstractIslandTeamCommand extends CompositeCommand {
protected final static boolean DEBUG = false;
protected static BiMap<UUID, UUID> inviteList = HashBiMap.create();
protected static BiMap<UUID, UUID> inviteList = HashBiMap.create();
// The time a player has to wait until they can reset their island again
protected static HashMap<UUID, Long> resetWaitTime = new HashMap<>();
protected static Set<UUID> leavingPlayers = new HashSet<>();
protected static Set<UUID> kickingPlayers = new HashSet<>();
// TODO: It would be good if these could be auto-provided
protected User user;
public AbstractIslandTeamCommand(CompositeCommand command, String label, String... aliases) {
super(command, label,aliases);
}
/**
* Sets a timeout for player into the Hashmap resetWaitTime
*

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,9 +72,11 @@ public class IslandTeamCommand extends AbstractIslandTeamCommand {
}
}
// Do some sanity checking
if (maxSize < 1) maxSize = 1;
if (maxSize < 1) {
maxSize = 1;
}
}
if (teamMembers.size() < maxSize) {
user.sendMessage("commands.island.team.invite.you-can-invite", "[number]", String.valueOf(maxSize - teamMembers.size()));
} else {

View File

@ -18,53 +18,58 @@ public class IslandTeamInviteAcceptCommand extends AbstractIslandTeamCommand {
public IslandTeamInviteAcceptCommand(IslandTeamInviteCommand islandTeamInviteCommand) {
super(islandTeamInviteCommand, "accept");
}
@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
public boolean execute(User user, List<String> args) {
Bukkit.getLogger().info("DEBUG: accept - " + inviteList.toString());
UUID playerUUID = user.getUniqueId();
if(!inviteList.containsKey(playerUUID))
return true;
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");
return true;
return false;
}
// Check if player is already in a team
if (getPlayers().inTeam(playerUUID)) {
user.sendMessage("commands.island.team.invite.errors.you-already-are-in-team");
return true;
return false;
}
// Get the team leader
UUID prospectiveTeamLeaderUUID = inviteList.get(playerUUID);
if (!getIslands().hasIsland(prospectiveTeamLeaderUUID)) {
user.sendMessage("commands.island.team.invite.errors.invalid-invite");
inviteList.remove(playerUUID);
return true;
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)
getPlugin().getLogger().info("DEBUG: After save " + getIslands().getIsland(prospectiveTeamLeaderUUID).getMembers().toString());
if (DEBUG) {
getPlugin().getLogger().info("DEBUG: After save " + getIslands().getIsland(prospectiveTeamLeaderUUID).getMemberSet().toString());
}
return true;
}

View File

@ -19,15 +19,17 @@ import us.tastybento.bskyblock.util.Util;
public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
private static final String NAME_PLACEHOLDER = "[name]";
public IslandTeamInviteCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "invite");
}
@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);
@ -37,50 +39,50 @@ public class IslandTeamInviteCommand extends AbstractIslandTeamCommand {
public boolean execute(User user, List<String> args) {
UUID playerUUID = user.getUniqueId();
// Player issuing the command must have an island
if (!getPlayers().hasIsland(playerUUID)) {
// If the player is in a team, they are not the leader
if (getPlayers().inTeam(playerUUID)) {
user.sendMessage("general.errors.not-leader");
}
user.sendMessage("general.errors.no-island");
boolean inTeam = getPlugin().getPlayers().inTeam(playerUUID);
UUID teamLeaderUUID = getPlugin().getIslands().getTeamLeader(playerUUID);
if (!(inTeam && teamLeaderUUID.equals(playerUUID))) {
user.sendMessage("general.errors.not-leader");
return false;
}
if (args.isEmpty() || args.size() > 1) {
// Invite label with no name, i.e., /island invite - tells the player who has invited them so far
if (inviteList.containsKey(playerUUID)) {
OfflinePlayer inviter = getPlugin().getServer().getOfflinePlayer(inviteList.get(playerUUID));
user.sendMessage("invite.nameHasInvitedYou", "[name]", inviter.getName());
} else {
user.sendMessage("help.island.invite");
user.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, inviter.getName());
return true;
}
return true;
// Show help
showHelp(this, user, args);
return false;
} else {
// Only online players can be invited
UUID invitedPlayerUUID = getPlayers().getUUID(args.get(0));
if (invitedPlayerUUID == null) {
user.sendMessage("general.errors.offline-player");
return true;
return false;
}
User invitedPlayer = User.getInstance(invitedPlayerUUID);
if (!invitedPlayer.isOnline()) {
user.sendMessage("general.errors.offline-player");
return true;
return false;
}
// Player cannot invite themselves
if (playerUUID.equals(invitedPlayerUUID)) {
user.sendMessage("invite.error.YouCannotInviteYourself");
return true;
user.sendMessage("commands.island.team.invite.cannot-invite-self");
return false;
}
// Check if this player can be invited to this island, or
// whether they are still on cooldown
long time = getPlayers().getInviteCoolDownTime(invitedPlayerUUID, getIslands().getIslandLocation(playerUUID));
if (time > 0 && !user.isOp()) {
user.sendMessage("invite.error.CoolDown", "[time]", String.valueOf(time));
return true;
user.sendMessage("commands.island.team.invite.cooldown", "[time]", String.valueOf(time));
return false;
}
// Player cannot invite someone already on a team
if (getPlayers().inTeam(invitedPlayerUUID)) {
user.sendMessage("invite.error.ThatPlayerIsAlreadyInATeam");
return true;
user.sendMessage("commands.island.team.invite.already-on-team");
return false;
}
Set<UUID> teamMembers = getMembers(user);
// Check if player has space on their team
@ -104,14 +106,16 @@ 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.
// Players can only have one invite one at a time - interesting
if (inviteList.containsValue(playerUUID)) {
inviteList.inverse().remove(playerUUID);
user.sendMessage("invite.removingInvite");
user.sendMessage("commands.island.team.invite.removing-invite");
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
@ -120,22 +124,25 @@ 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);
user.sendMessage("invite.inviteSentTo", "[name]", args.get(0));
user.sendMessage("commands.island.team.invite.invitation-sent", NAME_PLACEHOLDER, args.get(0));
// Send message to online player
invitedPlayer.sendMessage("invite.nameHasInvitedYou", "[name]", user.getName());
invitedPlayer.sendMessage("invite.toAcceptOrReject", "[label]", getLabel());
invitedPlayer.sendMessage("commands.island.team.invite.name-has-invited-you", NAME_PLACEHOLDER, user.getName());
invitedPlayer.sendMessage("commands.island.team.invite.to-accept-or-reject", "[label]", getLabel());
if (getPlayers().hasIsland(invitedPlayer.getUniqueId())) {
invitedPlayer.sendMessage("invite.warningYouWillLoseIsland");
invitedPlayer.sendMessage("commands.island.team.invite.you-will-lose-your-island");
}
return true;
} else {
user.sendMessage("invite.error.YourIslandIsFull");
user.sendMessage("commands.island.team.invite.errors.island-is-full");
return false;
}
}
return false;
}
@Override

View File

@ -13,12 +13,12 @@ public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
public IslandTeamInviteRejectCommand(IslandTeamInviteCommand islandTeamInviteCommand) {
super(islandTeamInviteCommand, "reject");
}
@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 true;
if (event.isCancelled()) {
return false;
}
// Remove this player from the global invite list
inviteList.remove(user.getUniqueId());
@ -45,6 +47,7 @@ public class IslandTeamInviteRejectCommand extends AbstractIslandTeamCommand {
} else {
// Someone typed /island reject and had not been invited
user.sendMessage("commands.island.team.invite.errors.none-invited-you");
return false;
}
return true;
}

View File

@ -1,6 +1,5 @@
package us.tastybento.bskyblock.commands.island.teams;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ -21,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<>();
}
@ -40,18 +39,18 @@ public class IslandTeamKickCommand extends AbstractIslandTeamCommand {
}
// If args are not right, show help
if (args.size() != 1) {
this.getSubCommand("help").get().execute(user, new ArrayList<>());
return true;
showHelp(this, user, args);
return false;
}
// Get target
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player");
return true;
return true;
}
if (!getIslands().getMembers(user.getUniqueId()).contains(targetUUID)) {
user.sendMessage("general.errors.not-in-team");
return true;
return true;
}
if (!getSettings().isKickConfirmation() || kickSet.contains(targetUUID)) {
kickSet.remove(targetUUID);

View File

@ -11,18 +11,18 @@ import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.api.commands.User;
public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
Set<UUID> leaveSet;
public IslandTeamLeaveCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "leave");
}
@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<>();
}
@ -30,7 +30,7 @@ public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
public boolean execute(User user, List<String> args) {
if (!getPlayers().inTeam(user.getUniqueId())) {
user.sendMessage("general.errors.no-team");
return true;
return false;
}
if (!getSettings().isKickConfirmation() || leaveSet.contains(user.getUniqueId())) {
leaveSet.remove(user.getUniqueId());
@ -40,6 +40,7 @@ public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
}
getIslands().removePlayer(user.getUniqueId());
user.sendMessage("general.success");
return true;
} else {
user.sendMessage("commands.island.team.leave.type-again");
leaveSet.add(user.getUniqueId());
@ -50,8 +51,8 @@ public class IslandTeamLeaveCommand extends AbstractIslandTeamCommand {
leaveSet.remove(user.getUniqueId());
user.sendMessage("general.errors.command-cancelled");
}}.runTaskLater(getPlugin(), getSettings().getKickWait());
return false;
}
return true;
}
}

View File

@ -10,13 +10,13 @@ public class IslandTeamPromoteCommand extends AbstractIslandTeamCommand {
public IslandTeamPromoteCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "promote");
}
@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

@ -21,13 +21,13 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
public IslandTeamSetownerCommand(IslandTeamCommand islandTeamCommand) {
super(islandTeamCommand, "setleader");
}
@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
@ -37,34 +37,35 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
boolean inTeam = getPlugin().getPlayers().inTeam(playerUUID);
UUID teamLeaderUUID = getPlugin().getIslands().getTeamLeader(playerUUID);
if (!(inTeam && teamLeaderUUID.equals(playerUUID))) {
return true;
user.sendMessage("general.errors.not-leader");
return false;
}
// If args are not right, show help
if (args.size() != 1) {
this.getSubCommand("help").get().execute(user, new ArrayList<>());
return true;
showHelp(this, user, args);
return false;
}
//getPlugin().getLogger().info("DEBUG: arg[0] = " + args.get(0));
UUID targetUUID = getPlayers().getUUID(args.get(0));
if (targetUUID == null) {
user.sendMessage("general.errors.unknown-player");
return true;
return false;
}
if (!getPlayers().inTeam(playerUUID)) {
user.sendMessage("general.errors.no-team");
return true;
return false;
}
if (!teamLeaderUUID.equals(playerUUID)) {
user.sendMessage("general.errors.not-leader");
return true;
return false;
}
if (targetUUID.equals(playerUUID)) {
user.sendMessage("commands.island.team.setowner.errors.cant-transfer-to-yourself");
return true;
return false;
}
if (!getPlugin().getIslands().getMembers(playerUUID).contains(targetUUID)) {
user.sendMessage("commands.island.team.setowner.errors.target-is-not-member");
return true;
return false;
}
// Fire event so add-ons can run commands, etc.
IslandBaseEvent event = TeamEvent.builder()
@ -74,7 +75,9 @@ public class IslandTeamSetownerCommand extends AbstractIslandTeamCommand {
.involvedPlayer(targetUUID)
.build();
getPlugin().getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return true;
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

@ -5,6 +5,7 @@ import java.sql.Connection;
import java.sql.SQLException;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
@ -36,10 +37,11 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
/**
* Loads a YAML file and if it does not exist it is looked for in the JAR
*
*
* @param fileName
* @return
*/
@Override
public YamlConfiguration loadYamlFile(String tableName, String fileName) {
if (!fileName.endsWith(".yml")) {
fileName = fileName + ".yml";
@ -52,7 +54,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
config = new YamlConfiguration();
config.load(yamlFile);
} catch (Exception e) {
e.printStackTrace();
Bukkit.getLogger().severe("Could not load yaml file from database " + tableName + " " + fileName + " " + e.getMessage());
}
} else {
// Create the missing file
@ -76,7 +78,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
/**
* Saves a YAML file
*
*
* @param yamlConfig
* @param fileName
*/
@ -93,7 +95,7 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
try {
yamlConfig.save(file);
} catch (Exception e) {
e.printStackTrace();
Bukkit.getLogger().severe("Could not save yaml file to database " + tableName + " " + fileName + " " + e.getMessage());
}
}

View File

@ -4,10 +4,12 @@ import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@ -26,11 +28,12 @@ import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.Constants;
import us.tastybento.bskyblock.Constants.GameType;
import us.tastybento.bskyblock.api.configuration.Adapter;
import us.tastybento.bskyblock.api.configuration.ConfigEntry;
import us.tastybento.bskyblock.api.configuration.StoreAt;
import us.tastybento.bskyblock.database.DatabaseConnecter;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.database.objects.adapters.Adapter;
import us.tastybento.bskyblock.database.objects.adapters.AdapterInterface;
import us.tastybento.bskyblock.util.Util;
/**
@ -90,7 +93,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
@Override
public boolean objectExits(String key) {
public boolean objectExists(String key) {
return databaseConnecter.uniqueIdExists(dataObject.getSimpleName(), key);
}
@ -106,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();
@ -163,37 +163,43 @@ 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);
// If there is a config annotation then do something
if (configEntry != null) {
if (configEntry != null) {
if (!configEntry.path().isEmpty()) {
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
if (!configEntry.adapter().equals(Adapter.class)) {
// A conversion adapter has been defined
Object value = config.get(storageLocation);
method.invoke(instance, ((Adapter<?,?>)configEntry.adapter().newInstance()).convertFrom(value));
if (DEBUG) {
plugin.getLogger().info("DEBUG: value = " + value);
plugin.getLogger().info("DEBUG: property type = " + propertyDescriptor.getPropertyType());
plugin.getLogger().info("DEBUG: " + value.getClass());
}
if (value != null && !value.getClass().equals(MemorySection.class)) {
method.invoke(instance, deserialize(value,propertyDescriptor.getPropertyType()));
}
// We are done here
continue;
}
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
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));
if (DEBUG) {
plugin.getLogger().info("DEBUG: value = " + value);
plugin.getLogger().info("DEBUG: property type = " + propertyDescriptor.getPropertyType());
plugin.getLogger().info("DEBUG: " + value.getClass());
}
if (value != null && !value.getClass().equals(MemorySection.class)) {
method.invoke(instance, deserialize(value,propertyDescriptor.getPropertyType()));
}
// We are done here
continue;
}
// Look in the YAML Config to see if this field exists (it should)
@ -210,12 +216,18 @@ 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()));
if (mapKey == null) {
continue;
}
// Map values can be null - it is allowed here
Object mapValue = deserialize(config.get(storageLocation + "." + key), Class.forName(valueType.getTypeName()));
if (DEBUG) {
plugin.getLogger().info("DEBUG: mapKey = " + mapKey + " (" + mapKey.getClass().getCanonicalName() + ")");
@ -229,49 +241,52 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
plugin.getLogger().info("DEBUG: is Set " + propertyDescriptor.getReadMethod().getGenericReturnType().getTypeName());
plugin.getLogger().info("DEBUG: adding a set");
}
// Loop through the collection resultset
// 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);
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.
//Set<Object> value = new HashSet((List<Object>) config.getList(storageLocation));
//Set<Object> value = new HashSet((List<Object>) config.getList(storageLocation));
method.invoke(instance, value);
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
//plugin.getLogger().info("DEBUG: is Set " + propertyDescriptor.getReadMethod().getGenericReturnType().getTypeName());
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding a set");
// Loop through the collection resultset
}
// 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));
//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());
@ -292,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);
@ -326,7 +342,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
// Run through all the fields in the class that is being stored. EVERY field must have a get and set method
fields:
fields:
for (Field field : dataObject.getDeclaredFields()) {
// Get the property descriptor for this field
@ -350,25 +366,31 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
if (!configEntry.path().isEmpty()) {
storageLocation = configEntry.path();
}
// TODO: add in game-specific saving
if (!configEntry.adapter().equals(Adapter.class)) {
// A conversion adapter has been defined
try {
config.set(storageLocation, ((Adapter<?,?>)configEntry.adapter().newInstance()).convertTo(value));
} catch (InstantiationException e) {
e.printStackTrace();
}
// We are done here
continue fields;
}
// TODO: add in game-specific saving
}
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
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));
} catch (InstantiationException e) {
plugin.getLogger().severe("Could not instatiate adapter " + adapterNotation.value().getName() + " " + e.getMessage());
}
// We are done here
continue fields;
}
//plugin.getLogger().info("DEBUG: property desc = " + propertyDescriptor.getPropertyType().getTypeName());
// Depending on the vale type, it'll need serializing differenty
// Check if this field is the mandatory UniqueId field. This is used to identify this instantiation of the class
if (method.getName().equals("getUniqueId")) {
// If the object does not have a unique name assigned to it already, one is created at random
// If the object does not have a unique name assigned to it already, one is created at random
//plugin.getLogger().info("DEBUG: uniqueId = " + value);
String id = (String)value;
if (value == null || id.isEmpty()) {
@ -377,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?
@ -396,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));
}
@ -414,7 +438,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
if (filename.isEmpty()) {
throw new IllegalArgumentException("No uniqueId in class");
}
databaseConnecter.saveYamlFile(config, path, filename);
databaseConnecter.saveYamlFile(config, path, filename);
}
/**
@ -447,11 +471,16 @@ 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) {
return null;
}
if (value instanceof String && value.equals("null")) {
// If the value is null as a string, return null
// If the value is null as a string, return null
return null;
}
// Bukkit may have deserialized the object already
@ -460,7 +489,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
}
// Types that need to be deserialized
if (clazz.equals(Long.class) && value.getClass().equals(Integer.class)) {
return new Long((Integer)value);
return new Long((Integer)value);
}
if (clazz.equals(UUID.class)) {
value = UUID.fromString((String)value);
@ -484,7 +513,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
} catch (Exception e) {
// Maybe this value does not exist?
// TODO return something?
e.printStackTrace();
plugin.getLogger().severe("Could not deserialize enum: " + clazz.getCanonicalName() + " " + value);
}
}
return value;
@ -502,8 +531,13 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
File dataFolder = new File(plugin.getDataFolder(), DATABASE_FOLDER_NAME);
File tableFolder = new File(dataFolder, dataObject.getSimpleName());
if (tableFolder.exists()) {
File file = new File(tableFolder, fileName);
file.delete();
try {
Files.delete(file.toPath());
} catch (IOException e) {
plugin.getLogger().severe("Could not delete yaml database object! " + file.getName() + " - " + e.getMessage());
}
}
}
@ -512,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

@ -130,7 +130,7 @@ public abstract class AbstractDatabaseHandler<T> {
* @param key
* @return true if this key exists
*/
public abstract boolean objectExits(String key);
public abstract boolean objectExists(String key);
/**
* Saves a file as settings

View File

@ -7,6 +7,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@ -30,7 +31,6 @@ public class PlayersManager{
private HashMap<UUID, Players> playerCache;
private Set<UUID> inTeleport;
private HashMap<String, UUID> nameCache;
/**
* Provides a memory cache of online player information
@ -61,7 +61,7 @@ public class PlayersManager{
playerCache.put(player.getPlayerUUID(), player);
}
} catch (Exception e) {
e.printStackTrace();
plugin.getLogger().severe("Could not load players from the database!" + e.getMessage());
}
}
@ -70,30 +70,33 @@ 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) {
e.printStackTrace();
plugin.getLogger().severe("Could not save player " + player.getPlayerName() + " "+ player.getUniqueId() + " " + e.getMessage());
}
}
};
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) {
e.printStackTrace();
plugin.getLogger().severe("Could not save player " + player.getPlayerName() + " "+ player.getUniqueId() + " " + e.getMessage());
}
}
}
@ -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 (handler.objectExists(playerUUID.toString())) {
if (DEBUG) {
plugin.getLogger().info("DEBUG: player in database");
}
try {
player = handler.loadObject(playerUUID.toString());
} catch (Exception e) {
e.printStackTrace();
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);
}
}
@ -159,26 +168,16 @@ public class PlayersManager{
*
*/
public void removeOnlinePlayer(final UUID player) {
// plugin.getLogger().info("Removing player from cache: " + player);
if (playerCache.containsKey(player)) {
try {
handler.saveObject(playerCache.get(player));
playerCache.remove(player);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | SecurityException
| InstantiationException | NoSuchMethodException
| IntrospectionException | SQLException e) {
e.printStackTrace();
}
}
save(player);
playerCache.remove(player);
}
/**
* Removes all players on the server now from cache and saves their info
* Saves all players on the server and clears the cache
*/
public void removeAllPlayers() {
for (UUID pl : playerCache.keySet()) {
removeOnlinePlayer(pl);
save(pl);
}
playerCache.clear();
}
@ -202,7 +201,7 @@ public class PlayersManager{
return true;
} else {
// Get from the database - do not add to cache yet
return handler.objectExits(uniqueID.toString());
return handler.objectExists(uniqueID.toString());
}
}
@ -341,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());
}
@ -355,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();
}
@ -373,14 +375,12 @@ 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
Island island = plugin.getIslands().getIslandAt(loc);
if (island != null) {
return island.getOwner();
}
return null;
// Look in the grid
Optional<Island> island = plugin.getIslands().getIslandAt(loc);
return island.map(x->x.getOwner()).orElse(null);
}
/**
@ -438,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();
}
@ -591,27 +593,22 @@ 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
| InvocationTargetException | SecurityException
| InstantiationException | NoSuchMethodException
| IntrospectionException | SQLException e) {
e.printStackTrace();
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");
}
}
}
public boolean isKnown(String string) {
UUID uuid = this.getUUID(string);
if (uuid == null) return false;
return false;
}
}

View File

@ -31,43 +31,52 @@ public class IslandCache {
private HashMap<UUID, Island> islandsByUUID;
// 2D islandGrid of islands, x,z
private TreeMap<Integer, TreeMap<Integer, Island>> islandGrid = new TreeMap<>();
public IslandCache() {
islandsByLocation = HashBiMap.create();
islandsByUUID = new HashMap<>();
}
/**
* Adds an island to the grid
* @param island
*/
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)
plugin.getLogger().info("DEBUG: island has " + island.getMembers().size() + " members");
for (UUID member: island.getMembers()) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: island has " + island.getMemberSet().size() + " members");
}
for (UUID member: island.getMemberSet()) {
if (DEBUG) {
plugin.getLogger().info("DEBUG: " + member);
}
islandsByUUID.put(member, island);
}
addToGrid(island);
}
public void addPlayer(UUID playerUUID, Island teamIsland) {
islandsByUUID.put(playerUUID, teamIsland);
}
/**
* Adds an island to the grid register
* @param newIsland
*/
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! ***");
@ -90,35 +99,38 @@ 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);
}
}
public void clear() {
islandsByLocation.clear();
islandsByUUID.clear();
}
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;
}
/**
* Create an island with no owner at location
* @param location
@ -126,19 +138,21 @@ public class IslandCache {
public Island createIsland(Location location){
return createIsland(location, null);
}
/**
* Create an island with owner. Note this does not create the schematic. It just creates the island data object.
* @param location
* @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;
}
@ -159,39 +173,44 @@ 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");
}
}
}
}
}
public Island get(Location location) {
return islandsByLocation.get(location);
}
public Island get(UUID uuid) {
return islandsByUUID.get(uuid);
}
/**
* Gets the island for this player. If they are in a team, the team island is returned
* @param uuid
@ -221,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;
@ -260,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;
}
@ -287,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.getMembers());
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;
}
@ -306,7 +330,7 @@ public class IslandCache {
if (DEBUG) {
plugin.getLogger().info("DEBUG: checking if " + playerUUID + " has an island");
plugin.getLogger().info("DEBUG: islandsByUUID : " + islandsByUUID.toString());
if (!islandsByUUID.containsKey(playerUUID)) {
plugin.getLogger().info("DEBUG: player is not in islandsByUUID");
} else {
@ -314,37 +338,43 @@ 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.getMembers().clear();
island.getMemberSet().clear();
island.setOwner(null);
}
island.getMembers().remove(playerUUID);
island.getMemberSet().remove(playerUUID);
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: removing reference to island by UUID");
}
islandsByUUID.remove(playerUUID);
}
public void setIslandName(UUID owner, String name) {
@ -352,7 +382,7 @@ public class IslandCache {
Island island = islandsByUUID.get(owner);
island.setName(name);
}
}
public int size() {
@ -370,8 +400,9 @@ public class IslandCache {
}
if (o instanceof Island) {
Island is = (Island)o;
if (is.getOwner() != null && islandsByUUID.containsKey(is.getOwner()));
return true;
if (is.getOwner() != null && islandsByUUID.containsKey(is.getOwner())) {
return true;
}
}
return false;
}

View File

@ -2,6 +2,7 @@ package us.tastybento.bskyblock.database.managers.island;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@ -26,7 +27,7 @@ import us.tastybento.bskyblock.database.BSBDatabase;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.util.DeleteIslandChunks;
import us.tastybento.bskyblock.util.SafeSpotTeleport;
import us.tastybento.bskyblock.util.SafeTeleportBuilder;
import us.tastybento.bskyblock.util.Util;
/**
@ -39,7 +40,6 @@ import us.tastybento.bskyblock.util.Util;
public class IslandsManager {
private static final boolean DEBUG = false;
private static final boolean DEBUG2 = false;
/**
* Checks if this location is safe for a player to teleport to. Used by
* warps and boat exits Unsafe is any liquid or air and also if there's no
@ -73,19 +73,19 @@ public class IslandsManager {
return false;
}
// In BSkyBlock, liquid may be unsafe
if (ground.isLiquid() || space1.isLiquid() || space2.isLiquid()) {
// Check if acid has no damage
if (plugin.getSettings().getAcidDamage() > 0D) {
// Bukkit.getLogger().info("DEBUG: acid");
return false;
} else if (ground.getType().equals(Material.STATIONARY_LAVA) || ground.getType().equals(Material.LAVA)
|| space1.getType().equals(Material.STATIONARY_LAVA) || space1.getType().equals(Material.LAVA)
|| space2.getType().equals(Material.STATIONARY_LAVA) || space2.getType().equals(Material.LAVA)) {
// Lava check only
// Bukkit.getLogger().info("DEBUG: lava");
return false;
}
// Check if acid has no damage
if (plugin.getSettings().getAcidDamage() > 0D && (ground.isLiquid() || space1.isLiquid() || space2.isLiquid())) {
// Bukkit.getLogger().info("DEBUG: acid");
return false;
}
if (ground.getType().equals(Material.STATIONARY_LAVA) || ground.getType().equals(Material.LAVA)
|| space1.getType().equals(Material.STATIONARY_LAVA) || space1.getType().equals(Material.LAVA)
|| space2.getType().equals(Material.STATIONARY_LAVA) || space2.getType().equals(Material.LAVA)) {
// Lava check only
// Bukkit.getLogger().info("DEBUG: lava");
return false;
}
MaterialData md = ground.getState().getData();
if (md instanceof SimpleAttachableMaterialData) {
//Bukkit.getLogger().info("DEBUG: trapdoor/button/tripwire hook etc.");
@ -160,11 +160,12 @@ public class IslandsManager {
height = i;
depth = i;
} else {
Island island = getIslandAt(l);
if (island == null) {
Optional<Island> island = getIslandAt(l);
if (!island.isPresent()) {
return null;
}
i = island.getProtectionRange();
i = island.get().getProtectionRange();
height = l.getWorld().getMaxHeight() - l.getBlockY();
depth = l.getBlockY();
}
@ -223,7 +224,7 @@ public class IslandsManager {
if (maxYradius < height) {
maxYradius++;
}
//plugin.getLogger().info("DEBUG: Radii " + minXradius + "," + minYradius + "," + minZradius +
//plugin.getLogger().info("DEBUG: Radii " + minXradius + "," + minYradius + "," + minZradius +
// "," + maxXradius + "," + maxYradius + "," + maxZradius);
} while (minXradius < i || maxXradius < i || minZradius < i || maxZradius < i || minYradius < depth
|| maxYradius < height);
@ -245,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()));
}
@ -256,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);
@ -270,7 +273,7 @@ public class IslandsManager {
try {
handler.deleteObject(island);
} catch (Exception e) {
e.printStackTrace();
plugin.getLogger().severe("Could not delete island from database! " + e.getMessage());
}
// Remove blocks from world
new DeleteIslandChunks(plugin, island);
@ -290,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);
@ -344,28 +348,28 @@ public class IslandsManager {
}
/**
* Returns the island at the location or null if there is none.
* Returns the island at the location or Optional empty if there is none.
* This includes the full island space, not just the protected area
*
* @param location
* @return Island object
*/
public Island getIslandAt(Location location) {
public Optional<Island> getIslandAt(Location location) {
if (location == null) {
//plugin.getLogger().info("DEBUG: location is null");
return null;
return Optional.empty();
}
// World check
if (!Util.inWorld(location)) {
//plugin.getLogger().info("DEBUG: not in right world");
return null;
return Optional.empty();
}
// Check if it is spawn
if (spawn != null && spawn.onIsland(location)) {
//plugin.getLogger().info("DEBUG: spawn");
return spawn;
return Optional.of(spawn);
}
return getIslandAt(location.getBlockX(), location.getBlockZ());
return Optional.ofNullable(getIslandAt(location.getBlockX(), location.getBlockZ()));
}
/**
@ -376,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;
}
@ -405,31 +410,20 @@ public class IslandsManager {
}
/**
* Returns the island being public at the location or null if there is none
* Returns the island being public at the location or Optional Empty if there is none
*
* @param location
* @return Island object
* @return Optional Island object
*/
public Island getProtectedIslandAt(Location location) {
public Optional<Island> getProtectedIslandAt(Location location) {
//plugin.getLogger().info("DEBUG: getProtectedIslandAt " + location);
// Try spawn
if (spawn != null && spawn.onIsland(location)) {
return spawn;
return Optional.of(spawn);
}
Island island = getIslandAt(location);
if (island == null) {
if (DEBUG2)
plugin.getLogger().info("DEBUG: no island at this location");
return null;
}
if (island.onIsland(location)) {
if (DEBUG2)
plugin.getLogger().info("DEBUG: on island");
return island;
}
if (DEBUG2)
plugin.getLogger().info("DEBUG: not in island protection zone");
return null;
Optional<Island> island = getIslandAt(location);
return island.map(x->x.onIsland(location) ? island.get() : null);
}
/**
@ -449,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;
@ -466,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);
@ -508,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)) {
@ -537,8 +543,9 @@ public class IslandsManager {
return n;
}
}
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: unsuccessful");
}
// Unsuccessful
return null;
}
@ -552,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();
}
@ -580,8 +588,8 @@ public class IslandsManager {
* @param player
* @return true if the home teleport is successful
*/
public boolean homeTeleport(final Player player) {
return homeTeleport(player, 1);
public void homeTeleport(final Player player) {
homeTeleport(player, 1);
}
/**
@ -592,13 +600,15 @@ public class IslandsManager {
* @return true if successful, false if not
*/
@SuppressWarnings("deprecation")
public boolean homeTeleport(final Player player, int number) {
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();
@ -611,17 +621,22 @@ 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 true;
new SafeTeleportBuilder(plugin).entity(player)
.island(plugin.getIslands().getIsland(player.getUniqueId()))
.portal(false)
.homeNumber(number)
.build();
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);
User user = User.getInstance(player);
if (number == 1) {
user.sendMessage("commands.island.go.teleport", "[label]", Constants.ISLANDCOMMAND);
@ -632,7 +647,7 @@ public class IslandsManager {
if (player.getGameMode().equals(GameMode.SPECTATOR)) {
player.setGameMode(GameMode.SURVIVAL);
}
return true;
return;
}
/**
@ -654,12 +669,14 @@ 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
if (!location.getBlock().isEmpty() && !location.getBlock().isLiquid()) {
@ -672,7 +689,7 @@ public class IslandsManager {
for (int x = -5; x <= 5; x++) {
for (int y = 10; y <= 255; y++) {
for (int z = -5; z <= 5; z++) {
if (!location.getWorld().getBlockAt(x + location.getBlockX(), y, z + location.getBlockZ()).isEmpty()
if (!location.getWorld().getBlockAt(x + location.getBlockX(), y, z + location.getBlockZ()).isEmpty()
&& !location.getWorld().getBlockAt(x + location.getBlockX(), y, z + location.getBlockZ()).isLiquid()) {
plugin.getLogger().info("Solid block found during long search - adding ");
createIsland(location);
@ -687,19 +704,19 @@ public class IslandsManager {
/**
* This returns the coordinate of where an island should be on the grid.
*
*
* @param location location to query
* @return Location of closest island
*/
public Location getClosestIsland(Location location) {
long x = Math.round((double) location.getBlockX() / plugin.getSettings().getIslandDistance())
long x = Math.round((double) location.getBlockX() / plugin.getSettings().getIslandDistance())
* plugin.getSettings().getIslandDistance() + plugin.getSettings().getIslandXOffset();
long z = Math.round((double) location.getBlockZ() / plugin.getSettings().getIslandDistance())
long z = Math.round((double) location.getBlockZ() / plugin.getSettings().getIslandDistance())
* plugin.getSettings().getIslandDistance() + plugin.getSettings().getIslandZOffset();
long y = plugin.getSettings().getIslandHeight();
return new Location(location.getWorld(), x, y, z);
}
/**
* @param uniqueId
* @return true if the player is the owner of their island, i.e., owner or team leader
@ -718,15 +735,20 @@ 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)
plugin.getLogger().info("DEBUG: addin island at "+ island.getCenter());
if (DEBUG) {
plugin.getLogger().info("DEBUG: adding island at "+ island.getCenter());
}
islandCache.addIsland(island);
}
} catch (Exception e) {
e.printStackTrace();
plugin.getLogger().severe("Could not load islands to cache! " + e.getMessage());
}
if (DEBUG) {
plugin.getLogger().info("DEBUG: islands loaded");
}
}
@ -739,7 +761,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
@ -760,15 +782,8 @@ public class IslandsManager {
// Must be in the same world as the locations being checked
// Note that getWorld can return null if a world has been deleted on the server
if (islandTestLocation != null && islandTestLocation.getWorld() != null && islandTestLocation.getWorld().equals(loc.getWorld())) {
int protectionRange = plugin.getSettings().getIslandProtectionRange();
if (getIslandAt(islandTestLocation) != null) {
// Get the protection range for this location if possible
Island island = getProtectedIslandAt(islandTestLocation);
if (island != null) {
// We are in a protected island area.
protectionRange = island.getProtectionRange();
}
}
int protectionRange = getIslandAt(islandTestLocation).map(x->x.getProtectionRange())
.orElse(plugin.getSettings().getIslandProtectionRange());
if (loc.getX() > islandTestLocation.getX() - protectionRange
&& loc.getX() < islandTestLocation.getX() + protectionRange
&& loc.getZ() > islandTestLocation.getZ() - protectionRange
@ -793,15 +808,15 @@ public class IslandsManager {
return false;
}
// Get the player's island from the grid if it exists
Island island = getIslandAt(loc);
if (island != null) {
Optional<Island> island = getIslandAt(loc);
if (island.isPresent()) {
//plugin.getLogger().info("DEBUG: island here is " + island.getCenter());
// On an island in the grid
//plugin.getLogger().info("DEBUG: onIsland = " + island.onIsland(loc));
//plugin.getLogger().info("DEBUG: members = " + island.getMembers());
//plugin.getLogger().info("DEBUG: player UUID = " + player.getUniqueId());
if (island.onIsland(loc) && island.getMembers().contains(player.getUniqueId())) {
if (island.get().onIsland(loc) && island.get().getMemberSet().contains(player.getUniqueId())) {
//plugin.getLogger().info("DEBUG: allowed");
// In a protected zone but is on the list of acceptable players
return true;
@ -815,7 +830,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()));
}
@ -844,7 +859,7 @@ public class IslandsManager {
}
public void metrics_setCreatedCount(int count){
this.metrics_createdcount = count;
metrics_createdcount = count;
}
/**
@ -878,7 +893,7 @@ public class IslandsManager {
public boolean playerIsOnIsland(User user, boolean coop) {
return locationIsAtHome(user.getUniqueId(), coop, user.getLocation());
}
/**
* @param location
*/
@ -892,8 +907,9 @@ public class IslandsManager {
* @param playerUUID
*/
public void removePlayer(UUID playerUUID) {
if (DEBUG)
if (DEBUG) {
plugin.getLogger().info("DEBUG: removing player");
}
islandCache.removePlayer(playerUUID);
}
@ -935,17 +951,18 @@ public class IslandsManager {
* @param async - if true, saving will be done async
*/
public void save(boolean async){
Collection<Island> collection = islandCache.getIslands();
Collection<Island> collection = islandCache.getIslands();
if(async){
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) {
e.printStackTrace();
plugin.getLogger().severe("Could not save island to datavase when running async! " + e.getMessage());
}
}
};
@ -953,12 +970,13 @@ 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) {
e.printStackTrace();
plugin.getLogger().severe("Could not save island to datavase when running sync! " + e.getMessage());
}
}
}
@ -982,13 +1000,14 @@ 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) {
plugin.getLogger().info("DEBUG: new team member list:");
plugin.getLogger().info(teamIsland.getMembers().toString());
plugin.getLogger().info(teamIsland.getMemberSet().toString());
}
// Save the database
save(false);
@ -1005,8 +1024,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();
@ -47,7 +47,7 @@ public class NewIsland {
/**
* Start building a new island
* @param plugin
* @param plugin
* @return New island builder object
*/
public static Builder builder(BSkyBlock plugin) {
@ -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)
@ -153,7 +158,7 @@ public class NewIsland {
.setChestItems(plugin.getSettings().getChestItems())
.setType(IslandType.END)
.build();
}
}
// Teleport player to their island
plugin.getIslands().homeTeleport(player);
// Fire exit event
@ -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

@ -4,6 +4,7 @@ import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import us.tastybento.bskyblock.database.DatabaseConnecter;
@ -24,8 +25,7 @@ public class MySQLDatabaseConnecter implements DatabaseConnecter {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Bukkit.getLogger().severe("Could not instantiate JDBC driver! " + e.getMessage());
}
// jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
connectionUrl = "jdbc:mysql://" + dbSettings.getHost() + "/" + dbSettings.getDatabaseName() + "?autoReconnect=true&useSSL=false&allowMultiQueries=true";

View File

@ -34,6 +34,8 @@ import org.bukkit.plugin.Plugin;
import us.tastybento.bskyblock.database.DatabaseConnecter;
import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.database.objects.adapters.Adapter;
import us.tastybento.bskyblock.database.objects.adapters.AdapterInterface;
import us.tastybento.bskyblock.util.Util;
/**
@ -46,7 +48,6 @@ import us.tastybento.bskyblock.util.Util;
*/
public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
private static final boolean DEBUG = false;
/**
* Connection to the database
*/
@ -54,47 +55,48 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
/**
* This hashmap maps Java types to MySQL SQL types because they are not the same
*/
private static HashMap<String, String> mySQLmapping;
{
mySQLmapping = new HashMap<>();
mySQLmapping.put(boolean.class.getTypeName(), "BOOL");
mySQLmapping.put(byte.class.getTypeName(), "TINYINT");
mySQLmapping.put(short.class.getTypeName(), "SMALLINT");
mySQLmapping.put(int.class.getTypeName(), "INTEGER");
mySQLmapping.put(long.class.getTypeName(), "BIGINT");
mySQLmapping.put(double.class.getTypeName(), "DOUBLE PRECISION");
mySQLmapping.put(Boolean.class.getTypeName(), "BOOL");
mySQLmapping.put(Byte.class.getTypeName(), "TINYINT");
mySQLmapping.put(Short.class.getTypeName(), "SMALLINT");
mySQLmapping.put(Integer.class.getTypeName(), "INTEGER");
mySQLmapping.put(Long.class.getTypeName(), "BIGINT");
mySQLmapping.put(Double.class.getTypeName(), "DOUBLE PRECISION");
mySQLmapping.put(BigDecimal.class.getTypeName(), "DECIMAL(13,0)");
mySQLmapping.put(String.class.getTypeName(), "VARCHAR(254)");
mySQLmapping.put(Date.class.getTypeName(), "DATE");
mySQLmapping.put(Time.class.getTypeName(), "TIME");
mySQLmapping.put(Timestamp.class.getTypeName(), "TIMESTAMP");
mySQLmapping.put(UUID.class.getTypeName(), "VARCHAR(36)");
private static final HashMap<String, String> MYSQL_MAPPING = new HashMap<>();
private static final String STRING_MAP = "VARCHAR(254)";
static {
MYSQL_MAPPING.put(boolean.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(byte.class.getTypeName(), "TINYINT");
MYSQL_MAPPING.put(short.class.getTypeName(), "SMALLINT");
MYSQL_MAPPING.put(int.class.getTypeName(), "INTEGER");
MYSQL_MAPPING.put(long.class.getTypeName(), "BIGINT");
MYSQL_MAPPING.put(double.class.getTypeName(), "DOUBLE PRECISION");
MYSQL_MAPPING.put(Boolean.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(Byte.class.getTypeName(), "TINYINT");
MYSQL_MAPPING.put(Short.class.getTypeName(), "SMALLINT");
MYSQL_MAPPING.put(Integer.class.getTypeName(), "INTEGER");
MYSQL_MAPPING.put(Long.class.getTypeName(), "BIGINT");
MYSQL_MAPPING.put(Double.class.getTypeName(), "DOUBLE PRECISION");
MYSQL_MAPPING.put(BigDecimal.class.getTypeName(), "DECIMAL(13,0)");
MYSQL_MAPPING.put(String.class.getTypeName(), STRING_MAP);
MYSQL_MAPPING.put(Date.class.getTypeName(), "DATE");
MYSQL_MAPPING.put(Time.class.getTypeName(), "TIME");
MYSQL_MAPPING.put(Timestamp.class.getTypeName(), "TIMESTAMP");
MYSQL_MAPPING.put(UUID.class.getTypeName(), "VARCHAR(36)");
// Bukkit Mappings
mySQLmapping.put(Location.class.getTypeName(), "VARCHAR(254)");
mySQLmapping.put(World.class.getTypeName(), "VARCHAR(254)");
MYSQL_MAPPING.put(Location.class.getTypeName(), STRING_MAP);
MYSQL_MAPPING.put(World.class.getTypeName(), STRING_MAP);
// Collections are stored as additional tables. The boolean indicates whether there
// Collections are stored as additional tables. The boolean indicates whether there
// is any data in it or not (maybe)
mySQLmapping.put(Set.class.getTypeName(), "BOOL");
mySQLmapping.put(Map.class.getTypeName(), "BOOL");
mySQLmapping.put(HashMap.class.getTypeName(), "BOOL");
mySQLmapping.put(ArrayList.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(Set.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(Map.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(HashMap.class.getTypeName(), "BOOL");
MYSQL_MAPPING.put(ArrayList.class.getTypeName(), "BOOL");
// Enums
mySQLmapping.put(Enum.class.getTypeName(), "VARCHAR(254)");
MYSQL_MAPPING.put(Enum.class.getTypeName(), STRING_MAP);
}
/**
* Handles the connection to the database and creation of the initial database schema (tables) for
* the class that will be stored.
* the class that will be stored.
* @param plugin
* @param type - the type of class to be stored in the database. Must inherit DataObject
* @param databaseConnecter - authentication details for the database
@ -110,10 +112,8 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Check if the table exists in the database and if not, create it
try {
createSchema();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IntrospectionException | SQLException e) {
plugin.getLogger().severe("Could not create database schema! " + e.getMessage());
}
}
@ -123,72 +123,71 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws SQLException
*/
private void createSchema() throws IntrospectionException, SQLException {
PreparedStatement pstmt = null;
try {
String sql = "CREATE TABLE IF NOT EXISTS `" + dataObject.getCanonicalName() + "` (";
// Run through the fields of the class using introspection
for (Field field : dataObject.getDeclaredFields()) {
// Get the description of the field
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
//plugin.getLogger().info("DEBUG: Field = " + field.getName() + "(" + propertyDescriptor.getPropertyType().getTypeName() + ")");
// Get default SQL mappings
// Get the write method for this field. This method will take an argument of the type of this field.
Method writeMethod = propertyDescriptor.getWriteMethod();
// The SQL column name is the name of the field
String columnName = field.getName();
// Get the mapping for this field from the hashmap
String typeName = propertyDescriptor.getPropertyType().getTypeName();
if (propertyDescriptor.getPropertyType().isEnum()) {
typeName = "Enum";
}
String mapping = mySQLmapping.get(typeName);
// If it exists, then create the SQL
if (mapping != null) {
// Note that the column name must be enclosed in `'s because it may include reserved words.
sql += "`" + columnName + "` " + mapping + ",";
// Create set and map tables if the type is a collection
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(Map.class) ||
propertyDescriptor.getPropertyType().equals(HashMap.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// The ID in this table relates to the parent table and is unique
String setSql = "CREATE TABLE IF NOT EXISTS `" + dataObject.getCanonicalName() + "." + field.getName() + "` ("
+ "uniqueId VARCHAR(36) NOT NULL, ";
// Get columns separated by commas
setSql += getCollectionColumnString(writeMethod,false,true);
// Close the SQL string
setSql += ")";
//plugin.getLogger().info(setSql);
// Execute the statement
PreparedStatement collections = connection.prepareStatement(setSql);
if (DEBUG)
plugin.getLogger().info("DEBUG: collections prepared statement = " + collections.toString());
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE IF NOT EXISTS `");
sql.append(dataObject.getCanonicalName());
sql.append("` (");
// Run through the fields of the class using introspection
for (Field field : dataObject.getDeclaredFields()) {
// Get the description of the field
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), dataObject);
// Get default SQL mappings
// Get the write method for this field. This method will take an argument of the type of this field.
Method writeMethod = propertyDescriptor.getWriteMethod();
// The SQL column name is the name of the field
String columnName = field.getName();
// Get the mapping for this field from the hashmap
String typeName = propertyDescriptor.getPropertyType().getTypeName();
if (propertyDescriptor.getPropertyType().isEnum()) {
typeName = "Enum";
}
String mapping = MYSQL_MAPPING.get(typeName);
// If it exists, then create the SQL
if (mapping != null) {
// Note that the column name must be enclosed in `'s because it may include reserved words.
sql.append("`");
sql.append(columnName);
sql.append("` ");
sql.append(mapping);
sql.append(",");
// Create set and map tables if the type is a collection
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(Map.class) ||
propertyDescriptor.getPropertyType().equals(HashMap.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// The ID in this table relates to the parent table and is unique
StringBuilder setSql = new StringBuilder();
setSql.append("CREATE TABLE IF NOT EXISTS `");
setSql.append(dataObject.getCanonicalName());
setSql.append(".");
setSql.append(field.getName());
setSql.append("` (");
setSql.append("uniqueId VARCHAR(36) NOT NULL, ");
// Get columns separated by commas
setSql.append(getCollectionColumnString(writeMethod,false,true));
// Close the SQL string
setSql.append(")");
// Execute the statement
try (PreparedStatement collections = connection.prepareStatement(setSql.toString())) {
collections.executeUpdate();
}
} else {
// The Java type is not in the hashmap, so we'll just guess that it can be stored in a string
// This should NOT be used in general because every type should be in the hashmap
sql += field.getName() + " VARCHAR(254),";
plugin.getLogger().severe("Unknown type! Hoping it'll fit in a string!");
plugin.getLogger().severe(propertyDescriptor.getPropertyType().getTypeName());
}
} else {
// The Java type is not in the hashmap, so we'll just guess that it can be stored in a string
// This should NOT be used in general because every type should be in the hashmap
sql.append(field.getName());
sql.append(" ");
sql.append(STRING_MAP);
sql.append(",");
plugin.getLogger().severe("Unknown type! Hoping it'll fit in a string!");
plugin.getLogger().severe(propertyDescriptor.getPropertyType().getTypeName());
}
//plugin.getLogger().info("DEBUG: SQL before trim string = " + sql);
// For the main table for the class, the unique ID is the primary key
sql += " PRIMARY KEY (uniqueId))";
//plugin.getLogger().info("DEBUG: SQL string = " + sql);
// Prepare and execute the database statements
pstmt = connection.prepareStatement(sql);
if (DEBUG)
plugin.getLogger().info("DEBUG: pstmt = " + pstmt.toString());
}
// For the main table for the class, the unique ID is the primary key
sql.append(" PRIMARY KEY (uniqueId))");
// Prepare and execute the database statements
try (PreparedStatement pstmt = connection.prepareStatement(sql.toString())) {
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the database properly
MySQLDatabaseResourceCloser.close(pstmt);
MySQLDatabaseResourceCloser.close(pstmt);
}
}
@ -208,15 +207,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();
@ -239,18 +240,18 @@ 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)
plugin.getLogger().info("DEBUG: collection column string = " + sb.toString());
return sb.toString();
}
@ -263,15 +264,15 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
private List<String> getCollentionColumnList(Method method, boolean createSchema) {
List<String> columns = new ArrayList<>();
for (Entry<String,String> en : getCollectionColumnMap(method).entrySet()) {
String col = en.getKey();
StringBuilder col = new StringBuilder();
col.append(en.getKey());
if (createSchema) {
col += " " + en.getValue();
col.append(" ");
col.append(en.getValue());
}
columns.add(col);
if (DEBUG)
plugin.getLogger().info("DEBUG: collection columns = " + col);
columns.add(col.toString());
}
return columns;
}
@ -287,23 +288,22 @@ 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) {
// Get the actual type arguments of the parameter
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
if (genericParameterType instanceof ParameterizedType) {
// Get the actual type arguments of the parameter
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;
for (Type type : parameters) {
// 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)
plugin.getLogger().info("DEBUG: collection column = " + "`" + type.getTypeName() + "_" + index + "`" + setMapping);
String setMapping = MYSQL_MAPPING.get(type.getTypeName());
// This column name format is typeName_# where # is a number incremented from 0
columns.put("`" + type.getTypeName() + "_" + index + "`", setMapping != null ? setMapping : STRING_MAP);
// Increment the index so each column has a unique name
index++;
}
// Increment the index so each column has a unique name
index++;
}
}
return columns;
@ -378,42 +378,32 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException, NoSuchMethodException {
Connection connection = null;
PreparedStatement preparedStatement = null;
if (DEBUG)
plugin.getLogger().info("DEBUG: saveObject ");
try {
// Try to connect to the database
connection = databaseConnecter.createConnection();
// insertQuery is created in super from the createInsertQuery() method
preparedStatement = connection.prepareStatement(insertQuery);
// insertQuery is created in super from the createInsertQuery() method
try (PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
// Get the uniqueId. As each class extends DataObject, it must have this method in it.
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", dataObject);
Method getUniqueId = propertyDescriptor.getReadMethod();
final String uniqueId = (String) getUniqueId.invoke(instance);
if (DEBUG) {
plugin.getLogger().info("DEBUG: Unique Id = " + uniqueId);
}
if (uniqueId.isEmpty()) {
throw new SQLException("uniqueId is blank");
}
// Create the insertion
int i = 0;
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)
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)
plugin.getLogger().info("DEBUG: value = " + value);
// Adapter Notation
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
// A conversion adapter has been defined
value = ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).deserialize(value);
}
// Create set and map table inserts if this is a Collection
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(Map.class) ||
@ -421,70 +411,75 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// Collection
// The table is cleared for this uniqueId every time the data is stored
String clearTableSql = "DELETE FROM `" + dataObject.getCanonicalName() + "." + field.getName() + "` WHERE uniqueId = ?";
PreparedStatement collStatement = connection.prepareStatement(clearTableSql);
collStatement.setString(1, uniqueId);
collStatement.execute();
if (DEBUG)
plugin.getLogger().info("DEBUG: collStatement " + collStatement.toString());
// Insert into the table
String setSql = "INSERT INTO `" + dataObject.getCanonicalName() + "." + field.getName() + "` (uniqueId, ";
// Get the columns we are going to insert, just the names of them
setSql += getCollectionColumnString(propertyDescriptor.getWriteMethod(), false, false) + ") ";
// Get all the ?'s for the columns
setSql += "VALUES ('" + uniqueId + "'," + getCollectionColumnString(propertyDescriptor.getWriteMethod(), true, false) + ")";
// Prepare the statement
collStatement = connection.prepareStatement(setSql);
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)) {
//plugin.getLogger().info("DEBUG: set class for ");
// Loop through the set or list
// Note that we have no idea what type this is
Collection<?> collection = (Collection<?>)value;
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
Object setValue = it.next();
//if (setValue instanceof UUID) {
// Serialize everything
setValue = serialize(setValue, setValue.getClass());
//}
// Set the value from ? to whatever it is
collStatement.setObject(1, setValue);
if (DEBUG)
plugin.getLogger().info("DEBUG: " + collStatement.toString());
// Execute the SQL in the database
collStatement.execute();
}
} else if (propertyDescriptor.getPropertyType().equals(Map.class) ||
propertyDescriptor.getPropertyType().equals(HashMap.class)) {
// Loop through the map
Map<?,?> collection = (Map<?,?>)value;
Iterator<?> it = collection.entrySet().iterator();
while (it.hasNext()) {
Entry<?,?> en = (Entry<?, ?>) it.next();
// Get the key and serialize it
Object key = serialize(en.getKey(), en.getKey().getClass());
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)
plugin.getLogger().info("DEBUG: mapValue = " + mapValue);
// Write the objects into prepared statement
collStatement.setObject(1, key);
collStatement.setObject(2, mapValue);
if (DEBUG)
plugin.getLogger().info("DEBUG: " + collStatement.toString());
// Write to database
collStatement.execute();
}
StringBuilder clearTableSql = new StringBuilder();
clearTableSql.append("DELETE FROM `");
clearTableSql.append(dataObject.getCanonicalName());
clearTableSql.append(".");
clearTableSql.append(field.getName());
clearTableSql.append("` WHERE uniqueId = ?");
try (PreparedStatement collStatement = connection.prepareStatement(clearTableSql.toString())) {
collStatement.setString(1, uniqueId);
collStatement.execute();
}
// Insert into the table
StringBuilder setSql = new StringBuilder();
setSql.append("INSERT INTO `");
setSql.append(dataObject.getCanonicalName());
setSql.append(".");
setSql.append(field.getName());
setSql.append("` (uniqueId, ");
// Get the columns we are going to insert, just the names of them
setSql.append(getCollectionColumnString(propertyDescriptor.getWriteMethod(), false, false));
setSql.append(") ");
// Get all the ?'s for the columns
setSql.append("VALUES ('?',");
setSql.append(getCollectionColumnString(propertyDescriptor.getWriteMethod(), true, false));
setSql.append(")");
// Prepare the statement
try (PreparedStatement collStatement = connection.prepareStatement(setSql.toString())) {
// Set the uniqueId
collStatement.setString(1, uniqueId);
// Do single dimension types (set and list)
if (propertyDescriptor.getPropertyType().equals(Set.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
//plugin.getLogger().info("DEBUG: set class for ");
// Loop through the set or list
// Note that we have no idea what type this is
Collection<?> collection = (Collection<?>)value;
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
Object setValue = it.next();
//if (setValue instanceof UUID) {
// Serialize everything
setValue = serialize(setValue, setValue.getClass());
//}
// Set the value from ? to whatever it is
collStatement.setObject(2, setValue);
// Execute the SQL in the database
collStatement.execute();
}
} else if (propertyDescriptor.getPropertyType().equals(Map.class) ||
propertyDescriptor.getPropertyType().equals(HashMap.class)) {
// Loop through the map
Map<?,?> collection = (Map<?,?>)value;
Iterator<?> it = collection.entrySet().iterator();
while (it.hasNext()) {
Entry<?,?> en = (Entry<?, ?>) it.next();
// Get the key and serialize it
Object key = serialize(en.getKey(), en.getKey().getClass());
// Get the value and serialize it
Object mapValue = serialize(en.getValue(), en.getValue().getClass());
// Write the objects into prepared statement
collStatement.setObject(1, key);
collStatement.setObject(2, mapValue);
// Write to database
collStatement.execute();
}
}
// Set value for the main insert. For collections, this is just a dummy value because the real values are in the
// additional table.
value = true;
}
// Set value for the main insert. For collections, this is just a dummy value because the real values are in the
// additional table.
value = true;
} else {
// If the value is not a collection, it just needs to be serialized to go into the database.
value = serialize(value, propertyDescriptor.getPropertyType());
@ -496,14 +491,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Add the statements to a batch
preparedStatement.addBatch();
// Execute
if (DEBUG)
plugin.getLogger().info("DEBUG: prepared statement = " + preparedStatement.toString());
preparedStatement.executeBatch();
} finally {
// Close properly
MySQLDatabaseResourceCloser.close(preparedStatement);
MySQLDatabaseResourceCloser.close(preparedStatement);
}
}
@ -568,26 +556,13 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException, ClassNotFoundException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = databaseConnecter.createConnection();
statement = connection.createStatement();
if (DEBUG)
plugin.getLogger().info("DEBUG: selectQuery = " + selectQuery);
resultSet = statement.executeQuery(selectQuery);
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery)) {
return createObjects(resultSet);
} finally {
MySQLDatabaseResourceCloser.close(resultSet);
MySQLDatabaseResourceCloser.close(statement);
MySQLDatabaseResourceCloser.close(connection);
}
}
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#selectObject(java.lang.String)
*/
@ -595,33 +570,29 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
public T loadObject(String uniqueId) throws InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
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";
PreparedStatement preparedStatement = connection.prepareStatement(query);
// Build the select query
StringBuilder query = new StringBuilder();
query.append("SELECT ");
query.append(getColumns(false));
query.append(" FROM `");
query.append(dataObject.getCanonicalName());
query.append("` WHERE uniqueId = ? LIMIT 1");
try (PreparedStatement preparedStatement = connection.prepareStatement(query.toString())) {
preparedStatement.setString(1, uniqueId);
if (DEBUG)
plugin.getLogger().info("DEBUG: load Object query = " + preparedStatement.toString());
resultSet = preparedStatement.executeQuery();
List<T> result = createObjects(resultSet);
if (!result.isEmpty()) {
return result.get(0);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
// If there is a result, we only want/need the first one
List<T> result = createObjects(resultSet);
if (!result.isEmpty()) {
return result.get(0);
}
}
return null;
} finally {
MySQLDatabaseResourceCloser.close(resultSet);
MySQLDatabaseResourceCloser.close(statement);
MySQLDatabaseResourceCloser.close(connection);
}
return null;
}
/**
*
* Creates a list of <T>s filled with values from the provided ResultSet
@ -648,7 +619,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()) {
@ -668,101 +639,85 @@ 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 the type is a Collection, then we need to deal with set and map tables
if (Collection.class.isAssignableFrom(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
//plugin.getLogger().info("DEBUG: Collection");
// TODO Get the values from the subsidiary tables.
// value is just of type boolean right now
String setSql = "SELECT ";
StringBuilder setSql = new StringBuilder();
setSql.append("SELECT ");
// Get the columns, just the names of them, no ?'s or types
setSql += getCollectionColumnString(method, false, false) + " ";
setSql += "FROM `" + dataObject.getCanonicalName() + "." + field.getName() + "` ";
setSql.append(getCollectionColumnString(method, false, false));
setSql.append(" ");
setSql.append("FROM `");
setSql.append(dataObject.getCanonicalName());
setSql.append(".");
setSql.append(field.getName());
setSql.append("` ");
// We will need to fill in the ? later with the unique id of the class from the database
setSql += "WHERE uniqueId = ?";
setSql.append("WHERE uniqueId = ?");
// Prepare the statement
PreparedStatement collStatement = connection.prepareStatement(setSql);
// Set the unique ID
collStatement.setObject(1, uniqueId);
if (DEBUG)
plugin.getLogger().info("DEBUG: collStatement = " + collStatement.toString());
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)
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>();
if (DEBUG) {
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
plugin.getLogger().info("DEBUG: setType = " + setType.getTypeName());
try (PreparedStatement collStatement = connection.prepareStatement(setSql.toString())) {
// Set the unique ID
collStatement.setObject(1, uniqueId);
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())) {
// 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<>();
while (collectionResultSet.next()) {
((Set<Object>) value).add(deserialize(collectionResultSet.getObject(1),Class.forName(setType.getTypeName())));
}
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// 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<>();
//plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
while (collectionResultSet.next()) {
// Add to the list
((List<Object>) value).add(deserialize(collectionResultSet.getObject(1),Class.forName(setType.getTypeName())));
}
} else if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType()) ||
HashMap.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
// 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<>();
while (collectionResultSet.next()) {
// Work through the columns
// Key
Object key = deserialize(collectionResultSet.getObject(1),Class.forName(keyType.getTypeName()));
Object mapValue = deserialize(collectionResultSet.getObject(2),Class.forName(valueType.getTypeName()));
((Map<Object,Object>) value).put(key,mapValue);
}
} else {
// Set value for the main insert. For collections, this is just a dummy value because the real values are in the
// additional table.
value = true;
}
}
while (collectionResultSet.next()) {
((Set<Object>) value).add(deserialize(collectionResultSet.getObject(1),Class.forName(setType.getTypeName())));
}
} else if (List.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
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>();
//plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
while (collectionResultSet.next()) {
//plugin.getLogger().info("DEBUG: adding to the list");
//plugin.getLogger().info("DEBUG: collectionResultSet size = " + collectionResultSet.getFetchSize());
((List<Object>) value).add(deserialize(collectionResultSet.getObject(1),Class.forName(setType.getTypeName())));
}
} else if (Map.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
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)
plugin.getLogger().info("DEBUG: collection type argument = " + collectionTypes);
while (collectionResultSet.next()) {
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)
plugin.getLogger().info("DEBUG: key = " + key);
Object mapValue = deserialize(collectionResultSet.getObject(2),Class.forName(valueType.getTypeName()));
if (DEBUG)
plugin.getLogger().info("DEBUG: value = " + mapValue);
((Map<Object,Object>) value).put(key,mapValue);
}
} else {
// Set value for the main insert. For collections, this is just a dummy value because the real values are in the
// additional table.
value = true;
}
} else {
if (DEBUG)
plugin.getLogger().info("DEBUG: regular type");
value = deserialize(value, propertyDescriptor.getPropertyType());
}
if (DEBUG) {
plugin.getLogger().info("DEBUG: invoking method " + method.getName());
if (value == null) {
plugin.getLogger().info("DEBUG: value = null");
} else {
plugin.getLogger().info("DEBUG: value class = " + value.getClass().getName());
}
// Adapter
// Check if there is an annotation on the field
Adapter adapterNotation = field.getAnnotation(Adapter.class);
if (adapterNotation != null && AdapterInterface.class.isAssignableFrom(adapterNotation.value())) {
// A conversion adapter has been defined
value = ((AdapterInterface<?,?>)adapterNotation.value().newInstance()).serialize(value);
}
// Write the value to the class
method.invoke(instance, value);
@ -782,10 +737,8 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object deserialize(Object value, Class<? extends Object> clazz) {
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
// If the value is null as a string, return null
return null;
}
// Types that need to be deserialized
@ -809,9 +762,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
Class<Enum> enumClass = (Class<Enum>)clazz;
value = Enum.valueOf(enumClass, (String)value);
} catch (Exception e) {
// Maybe this value does not exist?
// TODO return something?
e.printStackTrace();
plugin.getLogger().severe("Could not deserialize enum! " + e.getMessage());
}
}
return value;
@ -825,12 +776,8 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, IntrospectionException, SQLException, NoSuchMethodException, SecurityException {
// Delete this object from all tables
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// Try to connect to the database
connection = databaseConnecter.createConnection();
// Try to connect to the database
try (Connection conn = databaseConnecter.createConnection()){
// Get the uniqueId. As each class extends DataObject, it must have this method in it.
Method getUniqueId = dataObject.getMethod("getUniqueId");
String uniqueId = (String) getUniqueId.invoke(instance);
@ -841,13 +788,13 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Delete from the main table
// First substitution is the table name
// deleteQuery is created in super from the createInsertQuery() method
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "`"));
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
if (DEBUG)
plugin.getLogger().info("DEBUG: DELETE Query " + preparedStatement.toString());
preparedStatement.executeBatch();
try (PreparedStatement preparedStatement = conn.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "`"))) {
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
preparedStatement.executeBatch();
}
// Delete from any sub tables created from the object
// Run through the fields in the class using introspection
for (Field field : dataObject.getDeclaredFields()) {
@ -859,53 +806,39 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
propertyDescriptor.getPropertyType().equals(HashMap.class) ||
propertyDescriptor.getPropertyType().equals(ArrayList.class)) {
// First substitution is the table name
preparedStatement = connection.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "." + field.getName() + "`"));
// Second is the unique ID
preparedStatement.setString(1, uniqueId);
preparedStatement.addBatch();
// Execute
if (DEBUG)
plugin.getLogger().info("DEBUG: " + preparedStatement.toString());
preparedStatement.executeBatch();
try (PreparedStatement preparedStatement2 = conn.prepareStatement(deleteQuery.replace("[table_name]", "`" + dataObject.getCanonicalName() + "." + field.getName() + "`"))) {
// Second is the unique ID
preparedStatement2.setString(1, uniqueId);
preparedStatement2.addBatch();
// Execute
preparedStatement2.executeBatch();
}
}
}
} finally {
// Close properly
MySQLDatabaseResourceCloser.close(preparedStatement);
}
}
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#objectExits(java.lang.String)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#objectExists(java.lang.String)
*/
@Override
public boolean objectExits(String key) {
if (DEBUG)
plugin.getLogger().info("DEBUG: checking if " + key + " exists in the database");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT IF ( EXISTS( SELECT * FROM `" + dataObject.getCanonicalName() + "` WHERE `uniqueId` = ?), 1, 0)";
//String query = "SELECT * FROM `" + type.getCanonicalName() + "` WHERE uniqueId = ?";
try {
connection = databaseConnecter.createConnection();
preparedStatement = connection.prepareStatement(query);
public boolean objectExists(String key) {
// Create the query to see if this key exists
StringBuilder query = new StringBuilder();
query.append("SELECT IF ( EXISTS( SELECT * FROM `");
query.append(dataObject.getCanonicalName());
query.append("` WHERE `uniqueId` = ?), 1, 0)");
try (Connection conn = databaseConnecter.createConnection();
PreparedStatement preparedStatement = conn.prepareStatement(query.toString())) {
preparedStatement.setString(1, key);
resultSet = preparedStatement.executeQuery();
if (DEBUG)
plugin.getLogger().info("DEBUG: object exists sql " + preparedStatement.toString());
if (resultSet.next()) {
if (DEBUG)
plugin.getLogger().info("DEBUG: result is " + resultSet.getBoolean(1));
return resultSet.getBoolean(1);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getBoolean(1);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
MySQLDatabaseResourceCloser.close(resultSet);
MySQLDatabaseResourceCloser.close(preparedStatement);
MySQLDatabaseResourceCloser.close(connection);
plugin.getLogger().severe("Could not check if key exists in database! " + key + " " + e.getMessage());
}
return false;
}
@ -913,14 +846,14 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@Override
public void saveSettings(T instance)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
plugin.getLogger().severe("This method should not be used because configs are not stored in MySQL");
// This method should not be used because configs are not stored in MySQL
}
@Override
public T loadSettings(String uniqueId, T dbConfig) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException {
plugin.getLogger().severe("This method should not be used because configs are not stored in MySQL");
IllegalArgumentException, InvocationTargetException, ClassNotFoundException, IntrospectionException {
// This method should not be used because configs are not stored in MySQL
return null;
}

View File

@ -5,6 +5,8 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.bukkit.Bukkit;
public class MySQLDatabaseResourceCloser {
/**
@ -15,16 +17,16 @@ public class MySQLDatabaseResourceCloser {
*/
public static void close(ResultSet... resultSets) {
if (resultSets == null)
if (resultSets == null) {
return;
}
for (ResultSet resultSet : resultSets) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
/* Do some exception-logging here. */
e.printStackTrace();
Bukkit.getLogger().severe("Could not close MySQL resultset");
}
}
}
@ -42,16 +44,16 @@ public class MySQLDatabaseResourceCloser {
* CallableStatement, because they extend Statement.
*/
if (statements == null)
if (statements == null) {
return;
}
for (Statement statement : statements) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
/* Do some exception-logging here. */
e.printStackTrace();
Bukkit.getLogger().severe("Could not close MySQL statement");
}
}
}
@ -64,16 +66,16 @@ 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) {
try {
connection.close();
} catch (SQLException e) {
/* Do some exception-logging here. */
e.printStackTrace();
Bukkit.getLogger().severe("Could not close MySQL connection");
}
}
}

View File

@ -8,11 +8,11 @@ import us.tastybento.bskyblock.BSkyBlock;
*
*/
public interface DataObject {
default BSkyBlock getPlugin() {
return BSkyBlock.getInstance();
}
/**
* @return the uniqueId
*/
@ -22,5 +22,5 @@ public interface DataObject {
* @param uniqueId the uniqueId to set
*/
void setUniqueId(String uniqueId);
}

View File

@ -2,6 +2,7 @@ package us.tastybento.bskyblock.database.objects;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
@ -14,12 +15,17 @@ import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.events.IslandBaseEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.IslandLockEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.IslandUnlockEvent;
import us.tastybento.bskyblock.api.events.island.IslandEvent.Reason;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.database.objects.adapters.Adapter;
import us.tastybento.bskyblock.database.objects.adapters.FlagSerializer;
import us.tastybento.bskyblock.managers.RanksManager;
import us.tastybento.bskyblock.util.Pair;
import us.tastybento.bskyblock.util.Util;
/**
@ -34,19 +40,7 @@ public class Island implements DataObject {
private String uniqueId = "";
public String getUniqueId() {
// Island's have UUID's that are randomly assigned if they do not exist
if (uniqueId.isEmpty()) {
uniqueId = UUID.randomUUID().toString();
}
return uniqueId;
}
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
//// Island ////
//// Island ////
// The center of the island itself
private Location center;
@ -74,48 +68,42 @@ public class Island implements DataObject {
// Time parameters
private long createdDate;
private long updatedDate;
//// Team ////
// Owner (Team Leader)
private UUID owner;
// Members (use set because each value must be unique)
private Set<UUID> members = new HashSet<>();
private HashMap<UUID, Integer> members = new HashMap<>();
// Trustees
private Set<UUID> trustees = new HashSet<>();
// Coops
private Set<UUID> coops = new HashSet<>();
// Banned players
private Set<UUID> banned = new HashSet<>();
//// State ////
private boolean locked = false;
private boolean spawn = false;
private boolean purgeProtected = false;
//// Protection ////
private HashMap<Flag, Boolean> flags = new HashMap<>();
//// Protection flags ////
@Adapter(FlagSerializer.class)
private HashMap<Flag, Integer> flags = new HashMap<>();
private int levelHandicap;
private Location spawnPoint;
public Island() {}
public Island(Location location, UUID owner, int protectionRange) {
this.members.add(owner);
this.owner = owner;
this.createdDate = System.currentTimeMillis();
this.updatedDate = System.currentTimeMillis();
this.world = location.getWorld();
this.center = location;
this.range = BSkyBlock.getInstance().getSettings().getIslandProtectionRange();
this.minX = center.getBlockX() - range;
this.minZ = center.getBlockZ() - range;
setOwner(owner);
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;
}
/**
@ -123,10 +111,10 @@ public class Island implements DataObject {
* @param playerUUID
*/
public void addMember(UUID playerUUID) {
members.add(playerUUID);
banned.remove(playerUUID);
if (playerUUID != null) {
members.put(playerUUID, RanksManager.MEMBER_RANK);
}
}
/**
* Adds target to a list of banned players for this island. May be blocked by the event being cancelled.
* If the player is a member, coop or trustee, they will be removed from those lists.
@ -135,16 +123,9 @@ public class Island implements DataObject {
*/
public boolean addToBanList(UUID targetUUID) {
// TODO fire ban event
if (members.contains(targetUUID)) {
members.remove(targetUUID);
if (targetUUID != null) {
members.put(targetUUID, RanksManager.BANNED_RANK);
}
if (coops.contains(targetUUID)) {
coops.remove(targetUUID);
}
if (trustees.contains(targetUUID)) {
trustees.remove(targetUUID);
}
banned.add(targetUUID);
return true;
}
@ -152,7 +133,13 @@ public class Island implements DataObject {
* @return the banned
*/
public Set<UUID> getBanned() {
return banned;
Set<UUID> result = new HashSet<>();
for (Entry<UUID, Integer> member: members.entrySet()) {
if (member.getValue() <= RanksManager.BANNED_RANK) {
result.add(member.getKey());
}
}
return result;
}
/**
@ -162,76 +149,92 @@ public class Island implements DataObject {
return center;
}
/**
* @return the coop players of the island
*/
public Set<UUID> getCoops(){
return coops;
}
/**
* @return the date when the island was created
*/
public long getCreatedDate(){
return createdDate;
}
/**
* Get the Island Guard flag status
* Gets the rank needed to bypass this Island Guard flag
* @param flag
* @return true or false, or false if flag is not in the list
* @return the rank needed to bypass this flag. Players must have at least this rank to bypass this flag.
*/
public boolean getFlag(Flag flag){
public int getFlag(Flag flag){
if(flags.containsKey(flag)) {
return flags.get(flag);
} else {
flags.put(flag, false);
return false;
flags.put(flag, RanksManager.MEMBER_RANK);
return RanksManager.MEMBER_RANK;
}
}
/**
* @return the flags
*/
public HashMap<Flag, Boolean> getFlags() {
public HashMap<Flag, Integer> getFlags() {
return flags;
}
/**
* @return the levelHandicap
*/
public int getLevelHandicap() {
return levelHandicap;
}
/**
* @return true if the island is locked, otherwise false
*/
public boolean getLocked(){
return locked;
}
/**
* @return the members
*/
public HashMap<UUID, Integer> getMembers() {
return members;
}
/**
* @return the members of the island (owner included)
*/
public Set<UUID> getMembers(){
if (members == null) {
members = new HashSet<>();
public Set<UUID> getMemberSet(){
Set<UUID> result = new HashSet<>();
for (Entry<UUID, Integer> member: members.entrySet()) {
if (member.getValue() >= RanksManager.MEMBER_RANK) {
result.add(member.getKey());
}
}
return members;
return result;
}
/**
* @return the minProtectedX
*/
public int getMinProtectedX() {
public final int getMinProtectedX() {
return minProtectedX;
}
/**
* @return the minProtectedZ
*/
public int getMinProtectedZ() {
public final int getMinProtectedZ() {
return minProtectedZ;
}
/**
* @return the minX
*/
public int getMinX() {
public final int getMinX() {
return minX;
}
/**
* @return the minZ
*/
public int getMinZ() {
public final int getMinZ() {
return minZ;
}
@ -264,6 +267,13 @@ public class Island implements DataObject {
return protectionRange;
}
/**
* @return true if the island is protected from the Purge, otherwise false
*/
public boolean getPurgeProtected(){
return purgeProtected;
}
/**
* @return the island range
*/
@ -272,79 +282,20 @@ public class Island implements DataObject {
}
/**
* @return the trustees players of the island
* Get the rank of user for this island
* @param user
* @return rank integer
*/
public Set<UUID> getTrustees(){
return trustees;
public int getRank(User user) {
//Bukkit.getLogger().info("DEBUG: user UUID = " + user.getUniqueId());
return members.containsKey(user.getUniqueId()) ? members.get(user.getUniqueId()) : RanksManager.VISITOR_RANK;
}
/**
* @return the date when the island was updated (team member connection, etc...)
* @return the ranks
*/
public long getUpdatedDate(){
return updatedDate;
}
/**
* @return the world
*/
public World getWorld() {
return world;
}
/**
* @return the x coordinate of the island center
*/
public int getX(){
return center.getBlockX();
}
/**
* @return the y coordinate of the island center
*/
public int getY(){
return center.getBlockY();
}
/**
* @return the z coordinate of the island center
*/
public int getZ(){
return center.getBlockZ();
}
/**
* Checks if coords are in the island space
* @param x
* @param z
* @return true if in the island space
*/
public boolean inIslandSpace(int x, int z) {
//Bukkit.getLogger().info("DEBUG: center - " + center);
return (x >= minX && x < minX + range*2 && z >= minZ && z < minZ + range*2) ? true: false;
}
/**
* Check if banned
* @param targetUUID
* @return Returns true if target is banned on this island
*/
public boolean isBanned(UUID targetUUID) {
return banned.contains(targetUUID);
}
/**
* @return true if the island is locked, otherwise false
*/
public boolean getLocked(){
return locked;
}
/**
* @return true if the island is protected from the Purge, otherwise false
*/
public boolean getPurgeProtected(){
return purgeProtected;
public HashMap<UUID, Integer> getRanks() {
return members;
}
/**
@ -354,255 +305,8 @@ public class Island implements DataObject {
return spawn;
}
/**
* Checks if a location is within this island's protected area
*
* @param target
* @return true if it is, false if not
*/
public boolean onIsland(Location target) {
if (center != null && center.getWorld() != null) {
if (target.getBlockX() >= minProtectedX && target.getBlockX() < (minProtectedX + protectionRange * 2)
&& target.getBlockZ() >= minProtectedZ && target.getBlockZ() < (minProtectedZ + protectionRange * 2)) {
return true;
}
}
return false;
}
/**
* Removes target from the banned list. May be cancelled by unban event.
* @param targetUUID
* @return true if successful, otherwise false.
*/
public boolean removeFromBanList(UUID targetUUID) {
// TODO fire unban event
banned.remove(targetUUID);
return true;
}
/**
* @param banned the banned to set
*/
public void setBanned(Set<UUID> banned) {
this.banned = banned;
}
/**
* @param center the center to set
*/
public void setCenter(Location center) {
this.center = center;
}
/**
* @param coops - the coops to set
*/
public void setCoops(Set<UUID> coops){
this.coops = coops;
}
/**
* @param createdDate - the createdDate to sets
*/
public void setCreatedDate(long createdDate){
this.createdDate = createdDate;
}
/**
* Set the Island Guard flag status
* @param flag
* @param value
*/
public void setFlag(Flag flag, boolean value){
flags.put(flag, value);
}
/**
* @param flags the flags to set
*/
public void setFlags(HashMap<Flag, Boolean> flags) {
this.flags = flags;
}
/**
* Resets the flags to their default as set in config.yml for this island
*/
public void setFlagsDefaults(){
/*for(SettingsFlag flag : SettingsFlag.values()){
this.flags.put(flag, Settings.defaultIslandSettings.get(flag));
}*/ //TODO default flags
}
/**
* Locks/Unlocks the island. May be cancelled by
* {@link IslandLockEvent} or {@link IslandUnlockEvent}.
* @param locked - the lock state to set
*/
public void setLocked(boolean locked){
if(locked){
// Lock the island
IslandBaseEvent event = IslandEvent.builder().island(this).reason(Reason.LOCK).build();
if(!event.isCancelled()){
this.locked = locked;
}
} else {
// Unlock the island
IslandBaseEvent event = IslandEvent.builder().island(this).reason(Reason.UNLOCK).build();
if(!event.isCancelled()){
this.locked = locked;
}
}
}
/**
* @param members - the members to set
*/
public void setMembers(Set<UUID> members){
//Bukkit.getLogger().info("DEBUG: members size = " + members.size());
this.members = members;
}
/**
* @param minProtectedX the minProtectedX to set
*/
public void setMinProtectedX(int minProtectedX) {
this.minProtectedX = minProtectedX;
}
/**
* @param minProtectedZ the minProtectedZ to set
*/
public void setMinProtectedZ(int minProtectedZ) {
this.minProtectedZ = minProtectedZ;
}
/**
* @param minX the minX to set
*/
public void setMinX(int minX) {
this.minX = minX;
}
/**
* @param minZ the minZ to set
*/
public void setMinZ(int minZ) {
this.minZ = minZ;
}
/**
* @param name - the display name to set
* Set to null to remove the display name
*/
public void setName(String name){
this.name = name;
}
/**
* Sets the owner of the island. If the owner was previous banned, they are unbanned
* @param owner - the owner/team leader to set
*/
public void setOwner(UUID owner){
this.owner = owner;
this.banned.remove(owner);
}
/**
* @param protectionRange the protectionRange to set
*/
public void setProtectionRange(int protectionRange) {
this.protectionRange = protectionRange;
}
/**
* @param purgeProtected - if the island is protected from the Purge
*/
public void setPurgeProtected(boolean purgeProtected){
this.purgeProtected = purgeProtected;
}
/**
* @param range - the range to set
*/
public void setRange(int range){
this.range = range;
}
/**
* @param isSpawn - if the island is the spawn
*/
public void setSpawn(boolean isSpawn){
this.spawn = isSpawn;
}
/**
* Resets the flags to their default as set in config.yml for the spawn
*/
public void setSpawnFlagsDefaults(){
/*for(SettingsFlag flag : SettingsFlag.values()){
this.flags.put(flag, Settings.defaultSpawnSettings.get(flag));
}*/ //TODO default flags
}
/**
* @param trustees - the trustees to set
*/
public void setTrustees(Set<UUID> trustees){
this.trustees = trustees;
}
/**
* @param updatedDate - the updatedDate to sets
*/
public void setUpdatedDate(long updatedDate){
this.updatedDate = updatedDate;
}
/**
* @param world the world to set
*/
public void setWorld(World world) {
this.world = world;
}
/**
* Toggles the Island Guard flag status if it is in the list
* @param flag
*/
public void toggleFlag(Flag flag){
if(flags.containsKey(flag)) {
flags.put(flag, !flags.get(flag));
}
}
/**
* @return the levelHandicap
*/
public int getLevelHandicap() {
return levelHandicap;
}
/**
* @param levelHandicap the levelHandicap to set
*/
public void setLevelHandicap(int levelHandicap) {
this.levelHandicap = levelHandicap;
}
/**
* @return true if island is locked, false if not
*/
public boolean isLocked() {
return locked;
}
/**
* @return spawn
*/
public boolean isSpawn() {
return spawn;
public Location getSpawnPoint() {
return spawnPoint;
}
/**
@ -649,6 +353,61 @@ 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()) {
uniqueId = UUID.randomUUID().toString();
}
return uniqueId;
}
/**
* @return the date when the island was updated (team member connection, etc...)
*/
public long getUpdatedDate(){
return updatedDate;
}
/**
* @return the world
*/
public World getWorld() {
return world;
}
/**
* @return the x coordinate of the island center
*/
public int getX(){
return center.getBlockX();
}
/**
* @return the y coordinate of the island center
*/
public int getY(){
return center.getBlockY();
}
/**
* @return the z coordinate of the island center
*/
public int getZ(){
return center.getBlockZ();
}
/**
* Checks if coords are in the island space
* @param x
* @param z
* @return true if in the island space
*/
public boolean inIslandSpace(int x, int z) {
//Bukkit.getLogger().info("DEBUG: center - " + center);
return x >= minX && x < minX + range*2 && z >= minZ && z < minZ + range*2;
}
public boolean inIslandSpace(Location location) {
if (Util.inWorld(location)) {
return inIslandSpace(location.getBlockX(), location.getBlockZ());
@ -656,16 +415,295 @@ public class Island implements DataObject {
return false;
}
/**
* Checks if the coords are in island space
* @param blockCoord
* @return true or false
*/
public boolean inIslandSpace(Pair<Integer, Integer> blockCoord) {
return inIslandSpace(blockCoord.x, blockCoord.z);
}
/**
* Check if the flag is allowed or not
* For flags that are for the island in general and not related to rank
* @param flag
* @return true if allowed, false if not
*/
public boolean isAllowed(Flag flag) {
return getFlag(flag) >= 0;
}
/**
* Check if a user is allowed to bypass the flag or not
* @param user - user
* @param flag - flag
* @return true if allowed, false if not
*/
public boolean isAllowed(User user, Flag flag) {
//Bukkit.getLogger().info("DEBUG: " + flag.getID() + " user score = " + getRank(user) + " flag req = "+ this.getFlagReq(flag));
return getRank(user) >= getFlag(flag);
}
/**
* Check if banned
* @param targetUUID
* @return Returns true if target is banned on this island
*/
public boolean isBanned(UUID targetUUID) {
return members.containsKey(targetUUID) && members.get(targetUUID).equals(RanksManager.BANNED_RANK);
}
/**
* @return true if island is locked, false if not
*/
public boolean isLocked() {
return locked;
}
/**
* @return spawn
*/
public boolean isSpawn() {
return spawn;
}
/**
* Checks if a location is within this island's protected area
*
* @param target
* @return true if it is, false if not
*/
public boolean onIsland(Location target) {
if (center != null && center.getWorld() != null) {
if (target.getBlockX() >= minProtectedX && target.getBlockX() < (minProtectedX + protectionRange * 2)
&& target.getBlockZ() >= minProtectedZ && target.getBlockZ() < (minProtectedZ + protectionRange * 2)) {
return true;
}
}
return false;
}
/**
* Removes target from the banned list. May be cancelled by unban event.
* @param targetUUID
* @return true if successful, otherwise false.
*/
public boolean removeFromBanList(UUID targetUUID) {
// TODO fire unban event
members.remove(targetUUID);
return true;
}
public void removeMember(UUID playerUUID) {
members.remove(playerUUID);
}
/**
* @param center the center to set
*/
public void setCenter(Location center) {
this.center = center;
}
/**
* @param createdDate - the createdDate to sets
*/
public void setCreatedDate(long createdDate){
this.createdDate = createdDate;
}
/**
* Set the Island Guard flag rank
* @param flag
* @param value - rank value. If the flag applies to the island, a positive number = true, negative = false
*/
public void setFlag(Flag flag, int value){
flags.put(flag, value);
}
/**
* @param flags the flags to set
*/
public void setFlags(HashMap<Flag, Integer> flags) {
this.flags = flags;
}
/**
* Resets the flags to their default as set in config.yml for this island
*/
public void setFlagsDefaults(){
/*for(SettingsFlag flag : SettingsFlag.values()){
this.flags.put(flag, Settings.defaultIslandSettings.get(flag));
}*/ //TODO default flags
}
/**
* @param levelHandicap the levelHandicap to set
*/
public void setLevelHandicap(int levelHandicap) {
this.levelHandicap = levelHandicap;
}
/**
* Locks/Unlocks the island. May be cancelled by
* {@link IslandLockEvent} or {@link IslandUnlockEvent}.
* @param locked - the lock state to set
*/
public void setLocked(boolean locked){
if(locked){
// Lock the island
IslandBaseEvent event = IslandEvent.builder().island(this).reason(Reason.LOCK).build();
if(!event.isCancelled()){
this.locked = locked;
}
} else {
// Unlock the island
IslandBaseEvent event = IslandEvent.builder().island(this).reason(Reason.UNLOCK).build();
if(!event.isCancelled()){
this.locked = locked;
}
}
}
/**
* @param members the members to set
*/
public void setMembers(HashMap<UUID, Integer> members) {
this.members = members;
}
/**
* @param minProtectedX the minProtectedX to set
*/
public final void setMinProtectedX(int minProtectedX) {
this.minProtectedX = minProtectedX;
}
/**
* @param minProtectedZ the minProtectedZ to set
*/
public final void setMinProtectedZ(int minProtectedZ) {
this.minProtectedZ = minProtectedZ;
}
/**
* @param minX the minX to set
*/
public final void setMinX(int minX) {
this.minX = minX;
}
/**
* @param minZ the minZ to set
*/
public final void setMinZ(int minZ) {
this.minZ = minZ;
}
/**
* @param name - the display name to set
* Set to null to remove the display name
*/
public void setName(String name){
this.name = name;
}
/**
* Sets the owner of the island.
* @param owner - the owner/team leader to set
*/
public void setOwner(UUID owner){
this.owner = owner;
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);
}
}
members.put(owner, RanksManager.OWNER_RANK);
}
/**
* @param protectionRange the protectionRange to set
*/
public void setProtectionRange(int protectionRange) {
this.protectionRange = protectionRange;
}
/**
* @param purgeProtected - if the island is protected from the Purge
*/
public void setPurgeProtected(boolean purgeProtected){
this.purgeProtected = purgeProtected;
}
/**
* @param range - the range to set
*/
public void setRange(int range){
this.range = range;
}
/**
* Set user's rank to an arbitrary rank value
* @param user
* @param rank
*/
public void setRank(User user, int rank) {
if (user.getUniqueId() != null) {
members.put(user.getUniqueId(), rank);
}
}
/**
* @param ranks the ranks to set
*/
public void setRanks(HashMap<UUID, Integer> ranks) {
members = ranks;
}
/**
* @param isSpawn - if the island is the spawn
*/
public void setSpawn(boolean isSpawn){
spawn = isSpawn;
}
/**
* Resets the flags to their default as set in config.yml for the spawn
*/
public void setSpawnFlagsDefaults(){
/*for(SettingsFlag flag : SettingsFlag.values()){
this.flags.put(flag, Settings.defaultSpawnSettings.get(flag));
}*/ //TODO default flags
}
public void setSpawnPoint(Location location) {
spawnPoint = location;
}
public Location getSpawnPoint() {
return spawnPoint;
@Override
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
public void removeMember(UUID playerUUID) {
this.members.remove(playerUUID);
/**
* @param updatedDate - the updatedDate to sets
*/
public void setUpdatedDate(long updatedDate){
this.updatedDate = updatedDate;
}
/**
* @param world the world to set
*/
public void setWorld(World world) {
this.world = world;
}
}

View File

@ -1,68 +0,0 @@
/**
*
*/
package us.tastybento.bskyblock.database.objects;
import java.util.HashMap;
import java.util.UUID;
import us.tastybento.bskyblock.api.commands.User;
/**
* A bean to hold name to UUID lookup
* @author tastybento
*
*/
public class NameToUUID implements DataObject {
public HashMap<String, UUID> namesToUUID;
public NameToUUID() {}
/**
* @return the namesToUUID
*/
public HashMap<String, UUID> getNamesToUUID() {
return namesToUUID;
}
/**
* @param namesToUUID the namesToUUID to set
*/
public void setNamesToUUID(HashMap<String, UUID> namesToUUID) {
this.namesToUUID = namesToUUID;
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.objects.DataObject#getUniqueId()
*/
@Override
public String getUniqueId() {
return "names-uuid";
}
/* (non-Javadoc)
* @see us.tastybento.bskyblock.database.objects.DataObject#setUniqueId(java.lang.String)
*/
@Override
public void setUniqueId(String uniqueId) {
// Do nothing
}
/**
* Add or update a name
* @param user
*/
public void addName(User user) {
this.namesToUUID.put(user.getName(), user.getUniqueId());
}
/**
* Get UUID for name
* @param name
* @return UUID or null if not found
*/
public UUID getUUID(String name) {
return this.namesToUUID.get(name);
}
}

View File

@ -31,21 +31,22 @@ public class Players implements DataObject {
public Players() {}
/**
* @param plugin
* @param plugin
* @param uniqueId
* Constructor - initializes the state variables
*
*/
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();
}
}
/**
@ -64,7 +65,7 @@ public class Players implements DataObject {
public Location getHomeLocation(int number) {
/*
Bukkit.getLogger().info("DEBUG: getting home location " + number);
Bukkit.getLogger().info("DEBUG: " + homeLocations.toString());
for (Entry<Integer, Location> en : homeLocations.entrySet()) {
Bukkit.getLogger().info("DEBUG: " + en.getKey() + " ==> " + en.getValue());
@ -148,7 +149,7 @@ public class Players implements DataObject {
}
/**
* Stores the numbered home location of the player. Numbering starts at 1.
* Stores the numbered home location of the player. Numbering starts at 1.
* @param location
* @param number
*/
@ -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

@ -0,0 +1,19 @@
package us.tastybento.bskyblock.database.objects.adapters;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* Denotes which adapter should be used to serialize or deserialize this field
* @author tastybento
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Adapter {
Class<?> value();
}

View File

@ -0,0 +1,26 @@
package us.tastybento.bskyblock.database.objects.adapters;
/**
* Convert from to S or to V
* @author tastybento
*
* @param <S>
* @param <V>
*/
public interface AdapterInterface<S,V> {
/**
* Serialize object
* @param object - object
* @return serialized object
*/
S serialize(Object object);
/**
* Deserialize object
* @param object
* @return deserialized object
*/
V deserialize(Object object);
}

View File

@ -0,0 +1,58 @@
package us.tastybento.bskyblock.database.objects.adapters;
import java.util.HashMap;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.configuration.MemorySection;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.flags.Flag;
/**
* Serializes the {@link us.tastybento.bskyblock.database.objects.Island#getFlags() getFlags()} and
* {@link us.tastybento.bskyblock.database.objects.Island#setFlags() setFlags()}
* in {@link us.tastybento.bskyblock.database.objects.Island}
* @author tastybento
*
*/
public class FlagSerializer implements AdapterInterface<HashMap<Flag, Integer>, HashMap<String, Integer>> {
@Override
public HashMap<Flag, Integer> serialize(Object object) {
HashMap<Flag, Integer> result = new HashMap<>();
if (object == null) {
return result;
}
// For YAML
if (object instanceof MemorySection) {
MemorySection section = (MemorySection) object;
for (String key : section.getKeys(false)) {
Bukkit.getLogger().info("DEBUG: " + key + " = " + section.getInt(key));
result.put(BSkyBlock.getInstance().getFlagsManager().getFlagByID(key), section.getInt(key));
}
} else {
for (Entry<String, Integer> en : ((HashMap<String, Integer>)object).entrySet()) {
result.put(BSkyBlock.getInstance().getFlagsManager().getFlagByID(en.getKey()), en.getValue());
}
}
return result;
}
@Override
public HashMap<String, Integer> deserialize(Object object) {
HashMap<String, Integer> result = new HashMap<>();
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());
}
return result;
}
}

View File

@ -0,0 +1,34 @@
package us.tastybento.bskyblock.database.objects.adapters;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.potion.PotionEffectType;
public class PotionEffectListAdapter implements AdapterInterface<List<PotionEffectType>, List<String>> {
@SuppressWarnings("unchecked")
@Override
public List<PotionEffectType> serialize(Object from) {
List<PotionEffectType> result = new ArrayList<>();
if (from instanceof ArrayList) {
for (String type: (ArrayList<String>)from) {
result.add(PotionEffectType.getByName(type));
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<String> deserialize(Object to) {
List<String> result = new ArrayList<>();
if (to instanceof ArrayList) {
for (PotionEffectType type: (ArrayList<PotionEffectType>)to) {
result.add(type.getName());
}
}
return result;
}
}

View File

@ -22,7 +22,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
BSkyBlock plugin;
Random rand = new Random();
PerlinOctaveGenerator gen;
/**
* @param plugin
*/
@ -91,7 +91,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
}
// Next three layers are a mix of netherrack and air
for (int y = 5; y < 8; y++) {
double r = gen.noise(x, maxHeight - y, z, 0.5, 0.5);
double r = gen.noise(x, (double)maxHeight - y, z, 0.5, 0.5);
if (r > 0D) {
result.setBlock(x, (maxHeight - y), z, Material.NETHERRACK);
} else {
@ -99,7 +99,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
}
}
// Layer 8 may be glowstone
double r = gen.noise(x, maxHeight - 8, z, random.nextFloat(), random.nextFloat());
double r = gen.noise(x, (double)maxHeight - 8, z, random.nextFloat(), random.nextFloat());
if (r > 0.5D) {
// Have blobs of glowstone
switch (random.nextInt(4)) {
@ -118,6 +118,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
for (int i = 0; i < random.nextInt(10); i++) {
result.setBlock(x, (maxHeight - 8 - i), z, Material.GLOWSTONE);
}
break;
case 3:
result.setBlock(x, (maxHeight - 8), z, Material.GLOWSTONE);
if (x > 3 && z > 3) {

View File

@ -9,10 +9,16 @@ import us.tastybento.bskyblock.BSkyBlock;
public class IslandWorld {
private static final String MULTIVERSE_SET_GENERATOR = "mv modify set generator ";
private static final String MULTIVERSE_IMPORT = "mv import ";
private static final String NETHER = "_nether";
private static final String THE_END = "_the_end";
private static final String CREATING = "Creating ";
private BSkyBlock plugin;
private static World islandWorld;
private static World netherWorld;
private static World endWorld;
private World islandWorld;
private World netherWorld;
private World endWorld;
/**
* Generates the Skyblock worlds.
@ -24,32 +30,32 @@ public class IslandWorld {
return;
}
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName()) == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s Island World...");
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s Island World...");
}
// Create the world if it does not exist
islandWorld = WorldCreator.name(plugin.getSettings().getWorldName()).type(WorldType.FLAT).environment(World.Environment.NORMAL).generator(new ChunkGeneratorWorld(plugin))
.createWorld();
// Make the nether if it does not exist
if (plugin.getSettings().isNetherGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + "_nether") == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s Nether...");
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + NETHER) == null) {
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s Nether...");
}
if (!plugin.getSettings().isNetherIslands()) {
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_nether").type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + NETHER).type(WorldType.NORMAL).environment(World.Environment.NETHER).createWorld();
} else {
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_nether").type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
netherWorld = WorldCreator.name(plugin.getSettings().getWorldName() + NETHER).type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
.environment(World.Environment.NETHER).createWorld();
}
}
// Make the end if it does not exist
if (plugin.getSettings().isEndGenerate()) {
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + "_the_end") == null) {
Bukkit.getLogger().info("Creating " + plugin.getName() + "'s End World...");
if (plugin.getServer().getWorld(plugin.getSettings().getWorldName() + THE_END) == null) {
Bukkit.getLogger().info(CREATING + plugin.getName() + "'s End World...");
}
if (!plugin.getSettings().isEndIslands()) {
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_the_end").type(WorldType.NORMAL).environment(World.Environment.THE_END).createWorld();
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + THE_END).type(WorldType.NORMAL).environment(World.Environment.THE_END).createWorld();
} else {
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + "_the_end").type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
endWorld = WorldCreator.name(plugin.getSettings().getWorldName() + THE_END).type(WorldType.FLAT).generator(new ChunkGeneratorWorld(plugin))
.environment(World.Environment.THE_END).createWorld();
}
}
@ -62,31 +68,30 @@ public class IslandWorld {
Bukkit.getLogger().info("Trying to register generator with Multiverse ");
try {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + plugin.getSettings().getWorldName() + " normal -g " + plugin.getName());
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + " normal -g " + plugin.getName());
if (!Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName())) {
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName())) {
Bukkit.getLogger().severe("Multiverse is out of date! - Upgrade to latest version!");
}
if (netherWorld != null && plugin.getSettings().isNetherGenerate() && plugin.getSettings().isNetherIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + plugin.getSettings().getWorldName() + "_nether nether -g " + plugin.getName());
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_nether nether -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName() + "_nether");
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + NETHER);
}
if (endWorld != null && plugin.getSettings().isEndGenerate() && plugin.getSettings().isEndIslands()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + plugin.getSettings().getWorldName() + "_the_end end -g " + plugin.getName());
MULTIVERSE_IMPORT + plugin.getSettings().getWorldName() + "_the_end end -g " + plugin.getName());
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv modify set generator " + plugin.getName() + " " + plugin.getSettings().getWorldName() + "_the_end");
MULTIVERSE_SET_GENERATOR + plugin.getName() + " " + plugin.getSettings().getWorldName() + THE_END);
}
} catch (Exception e) {
Bukkit.getLogger().severe("Not successfull! Disabling " + plugin.getName() + "!");
e.printStackTrace();
Bukkit.getServer().getPluginManager().disablePlugin(plugin);
}
}
}
/**
@ -104,7 +109,7 @@ public class IslandWorld {
*/
public World getNetherWorld() {
if (plugin.getSettings().isUseOwnGenerator()) {
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + "_nether");
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + NETHER);
}
return netherWorld;
}
@ -114,7 +119,7 @@ public class IslandWorld {
*/
public World getEndWorld() {
if (plugin.getSettings().isUseOwnGenerator()) {
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + "_the_end");
return Bukkit.getServer().getWorld(plugin.getSettings().getWorldName() + THE_END);
}
return endWorld;
}

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;
}
@ -109,7 +109,7 @@ public class IslandBuilder {
generateNetherBlocks();
} else if (type == IslandType.END){
generateEndBlocks();
}
}
// Do other stuff
}
@ -477,12 +477,12 @@ 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++) {
sign.setLine(i, user.getTranslation("new-island.sign.line" + i, "[player]", playerName));
}
}
((org.bukkit.material.Sign) sign.getData()).setFacingDirection(BlockFace.NORTH);
sign.update();
}

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());
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.getMembers().contains(playerUUID) && !user.hasPermission(Constants.PERMPREFIX + "mod.bypassprotect")) {
if (DEBUG)
}
if (!currentIsland.getMemberSet().contains(playerUUID) && !user.hasPermission(Constants.PERMPREFIX + "mod.bypassprotect")) {
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

@ -1,6 +1,7 @@
package us.tastybento.bskyblock.listeners;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.event.EventHandler;
@ -17,9 +18,7 @@ import us.tastybento.bskyblock.api.panels.Panel;
public class PanelListenerManager implements Listener {
//private static final boolean DEBUG = false;
public static HashMap<UUID, Panel> openPanels = new HashMap<>();
private static HashMap<UUID, Panel> openPanels = new HashMap<>();
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
@ -38,12 +37,12 @@ public class PanelListenerManager implements Listener {
if (slot == event.getRawSlot()) {
// Check that they left clicked on it
// TODO: in the future, we may want to support right clicking
if (panel.getItems().get(slot).getClickHandler().isPresent()) {
// Cancel the event if true was returned by the ClickHandler
event.setCancelled(panel.getItems().get(slot).getClickHandler().get().onClick(user, ClickType.LEFT));
panel.getItems().get(slot).getClickHandler().ifPresent(handler -> {
// Execute the handler's onClick method and optionally cancel the event if the handler returns true
event.setCancelled(handler.onClick(user, ClickType.LEFT));
// If there is a listener, then run it.
panel.getListener().ifPresent(l -> l.onInventoryClick(user, inventory, event.getCurrentItem()));
}
});
}
}
} else {
@ -55,12 +54,23 @@ public class PanelListenerManager implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClose(InventoryCloseEvent event) {
if (openPanels.containsKey(event.getPlayer().getUniqueId())) openPanels.remove(event.getPlayer().getUniqueId());
if (openPanels.containsKey(event.getPlayer().getUniqueId())) {
openPanels.remove(event.getPlayer().getUniqueId());
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onLogOut(PlayerQuitEvent event) {
if (openPanels.containsKey(event.getPlayer().getUniqueId())) openPanels.remove(event.getPlayer().getUniqueId());
if (openPanels.containsKey(event.getPlayer().getUniqueId())) {
openPanels.remove(event.getPlayer().getUniqueId());
}
}
/**
* @return the openPanels
*/
public static Map<UUID, Panel> getOpenPanels() {
return openPanels;
}
}

View File

@ -0,0 +1,225 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import java.lang.reflect.Method;
import java.util.Optional;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import us.tastybento.bskyblock.BSkyBlock;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.api.flags.Flag.FlagType;
import us.tastybento.bskyblock.database.managers.island.IslandsManager;
import us.tastybento.bskyblock.database.objects.Island;
/**
* Abstract class for flag listeners. Provides common code.
* @author tastybento
*
*/
public abstract class AbstractFlagListener implements Listener {
private BSkyBlock plugin = BSkyBlock.getInstance();
private User user = null;
/**
* @return the plugin
*/
public BSkyBlock getPlugin() {
return plugin;
}
/**
* Used for unit testing only to set the plugin
* @param plugin
*/
public void setPlugin(BSkyBlock plugin) {
this.plugin = plugin;
}
/**
* Sets the player associated with this event.
* If the user is a fake player, they are not counted.
* @param e - the event
* @return true if found, otherwise false
*/
private boolean createEventUser(Event e) {
try {
// Use reflection to get the getPlayer method if it exists
Method getPlayer = e.getClass().getMethod("getPlayer");
if (getPlayer != null) {
setUser(User.getInstance((Player)getPlayer.invoke(e)));
return true;
}
} catch (Exception e1) { // Do nothing
}
return false;
}
/**
* Explicitly set the user for the next {@link #checkIsland(Event, Location, Flag)} or {@link #checkIsland(Event, Location, Flag, boolean)}
* @param user
*/
public AbstractFlagListener setUser(User user) {
if (!plugin.getSettings().getFakePlayers().contains(user.getName())) {
this.user = user;
}
return this;
}
/*
* The following methods cover the cancellable events and enable a simple noGo(e) to be used to cancel and send the error message
*/
/**
* Cancels the event and sends the island public message to user
* @param e Event
*/
public void noGo(Event e) {
noGo(e, false);
}
/**
* Cancels the event and sends the island protected message to user unless silent is true
* @param e Event
* @param silent - if true, message is not sent
*/
public void noGo(Event e, boolean silent) {
if (e instanceof Cancellable) {
((Cancellable)e).setCancelled(true);
}
if (user != null) {
if (!silent) {
user.sendMessage("protection.protected");
}
user.updateInventory();
}
}
/**
* Check if loc is in the island worlds
* @param loc
* @return true if the location is in the island worlds
*/
public boolean inWorld(Location loc) {
return (loc.getWorld().equals(plugin.getIslandWorldManager().getIslandWorld())
|| loc.getWorld().equals(plugin.getIslandWorldManager().getNetherWorld())
|| loc.getWorld().equals(plugin.getIslandWorldManager().getEndWorld())) ? true : false;
}
/**
* Check if the entity is in the island worlds
* @param entity - the entity
* @return true if in world
*/
public boolean inWorld(Entity entity) {
return inWorld(entity.getLocation());
}
/**
* Check if user is in the island worlds
* @param user - a user
* @return true if in world
*/
public boolean inWorld(User user) {
return inWorld(user.getLocation());
}
/**
* Generic place blocks checker
* @param e
* @param loc
* @param breakBlocks
* @return true if the check is okay, false if it was disallowed
*/
public boolean checkIsland(Event e, Location loc, Flag breakBlocks) {
return checkIsland(e, loc, breakBlocks, false);
}
/**
* Check if flag is allowed
* @param e
* @param loc
* @param silent - if true, no attempt is made to tell the user
* @return true if the check is okay, false if it was disallowed
*/
public boolean checkIsland(Event e, Location loc, Flag flag, boolean silent) {
// If this is not an Island World, skip
if (!inWorld(loc)) {
return true;
}
// Get the island and if present
Optional<Island> island = getIslands().getIslandAt(loc);
// Handle Settings Flag
if (flag.getType().equals(FlagType.SETTING)) {
// If the island exists, return the setting, otherwise return the default setting for this flag
return island.map(x -> x.isAllowed(flag)).orElse(flag.isDefaultSetting());
}
// Protection flag
// If the user is not set already, try to get it from the event
if (user == null) {
// Set the user associated with this event
if (!createEventUser(e)) {
// The user is not set, and the event does not hold a getPlayer, so return false
// TODO: is this the correct handling here?
Bukkit.getLogger().severe("Check island had no associated user! " + e.getEventName());
return false;
}
}
if (island.isPresent()) {
if (!island.get().isAllowed(user, flag)) {
noGo(e, silent);
// Clear the user for the next time
user = null;
return false;
} else {
user = null;
return true;
}
}
// The player is in the world, but not on an island, so general world settings apply
if (!flag.isDefaultSetting()) {
noGo(e, silent);
user = null;
return false;
} else {
user = null;
return true;
}
}
/**
* Get the flag for this ID
* @param id
* @return Flag denoted by the id
*/
protected Flag id(String id) {
return plugin.getFlagsManager().getFlagByID(id);
}
/**
* Get the island database manager
* @return the island database manager
*/
protected IslandsManager getIslands() {
return plugin.getIslands();
}
}

View File

@ -0,0 +1,139 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import us.tastybento.bskyblock.lists.Flags;
/**
* @author ben
*
*/
public class BlockInteractionListener extends AbstractFlagListener {
/**
* Handle interaction with blocks
* @param e
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerInteract(final PlayerInteractEvent e) {
if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return;
}
switch (e.getClickedBlock().getType()) {
case ANVIL:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.ANVIL);
break;
case BEACON:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.BEACON);
break;
case BED_BLOCK:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.BED);
break;
case BREWING_STAND:
case CAULDRON:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.BREWING);
break;
case CHEST:
case STORAGE_MINECART:
case TRAPPED_CHEST:
case BLACK_SHULKER_BOX:
case BLUE_SHULKER_BOX:
case BROWN_SHULKER_BOX:
case CYAN_SHULKER_BOX:
case GRAY_SHULKER_BOX:
case GREEN_SHULKER_BOX:
case LIGHT_BLUE_SHULKER_BOX:
case LIME_SHULKER_BOX:
case PINK_SHULKER_BOX:
case MAGENTA_SHULKER_BOX:
case ORANGE_SHULKER_BOX:
case PURPLE_SHULKER_BOX:
case RED_SHULKER_BOX:
case SILVER_SHULKER_BOX:
case WHITE_SHULKER_BOX:
case YELLOW_SHULKER_BOX:
case DISPENSER:
case DROPPER:
case HOPPER:
case HOPPER_MINECART:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.CHEST);
break;
case ACACIA_DOOR:
case BIRCH_DOOR:
case DARK_OAK_DOOR:
case IRON_DOOR:
case IRON_DOOR_BLOCK:
case IRON_TRAPDOOR:
case JUNGLE_DOOR:
case SPRUCE_DOOR:
case TRAP_DOOR:
case WOODEN_DOOR:
case WOOD_DOOR:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.DOOR);
break;
case ACACIA_FENCE_GATE:
case BIRCH_FENCE_GATE:
case DARK_OAK_FENCE_GATE:
case FENCE_GATE:
case JUNGLE_FENCE_GATE:
case SPRUCE_FENCE_GATE:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.GATE);
break;
case BURNING_FURNACE:
case FURNACE:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.FURNACE);
break;
case ENCHANTMENT_TABLE:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.ENCHANTING);
break;
case ENDER_CHEST:
break;
case JUKEBOX:
case NOTE_BLOCK:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.MUSIC);
break;
case WORKBENCH:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.CRAFTING);
break;
case STONE_BUTTON:
case WOOD_BUTTON:
case LEVER:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.LEVER_BUTTON);
break;
case DIODE:
case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON:
case REDSTONE_COMPARATOR_ON:
case REDSTONE_COMPARATOR_OFF:
case DAYLIGHT_DETECTOR:
case DAYLIGHT_DETECTOR_INVERTED:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.REDSTONE);
break;
default:
break;
}
// Now check for in-hand items
if (e.getItem() != null) {
switch (e.getItem().getType()) {
case ENDER_PEARL:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.ENDER_PEARL);
break;
case MONSTER_EGG:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.SPAWN_EGGS);
break;
default:
break;
}
}
}
}

View File

@ -1,6 +1,141 @@
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.event.Listener;
import org.bukkit.Material;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.util.BlockIterator;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.lists.Flags;
public class BreakBlocksListener extends AbstractFlagListener {
/**
* Prevents blocks from being broken
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockBreak(final BlockBreakEvent e) {
checkIsland(e, e.getBlock().getLocation(), Flags.BREAK_BLOCKS);
}
/**
* Prevents the breakage of hanging items
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW)
public void onBreakHanging(final HangingBreakByEntityEvent e) {
if (e.getRemover() instanceof Player) {
setUser(User.getInstance(e.getRemover())).checkIsland(e, e.getEntity().getLocation(), Flags.BREAK_BLOCKS);
}
}
/**
* Handles breaking objects
*
* @param e
*/
@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;
}
// Look along player's sight line to see if any blocks are skulls
try {
BlockIterator iter = new BlockIterator(e.getPlayer(), 10);
Block lastBlock = iter.next();
while (iter.hasNext()) {
lastBlock = iter.next();
if (lastBlock.getType().equals(Material.SKULL)) {
checkIsland(e, lastBlock.getLocation(), Flags.BREAK_BLOCKS);
return;
}
}
} catch (Exception ex) {}
switch (e.getClickedBlock().getType()) {
case CAKE_BLOCK:
case DRAGON_EGG:
case MOB_SPAWNER:
checkIsland(e, e.getClickedBlock().getLocation(), Flags.BREAK_BLOCKS);
return;
case BED_BLOCK:
if (e.getPlayer().getWorld().getEnvironment().equals(Environment.NETHER)) {
// Prevent explosions checkIsland(e, e.getClickedBlock().getLocation(), Flags.BREAK_BLOCKS);
return;
}
break;
default:
break;
}
}
/**
* Handles vehicle breaking
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onVehicleDamageEvent(VehicleDamageEvent e) {
if (inWorld(e.getVehicle()) && e.getAttacker() instanceof Player) {
User user = User.getInstance((Player) e.getAttacker());
// Get the island and if present, check the flag, react if required and return
getIslands().getIslandAt(e.getVehicle().getLocation()).ifPresent(x -> {
if (!x.isAllowed(user, Flags.BREAK_BLOCKS)) {
e.setCancelled(true);
user.sendMessage("protection.protected");
}
return;
});
// The player is in the world, but not on an island, so general world settings apply
if (!Flags.BREAK_BLOCKS.isDefaultSetting()) {
e.setCancelled(true);
user.sendMessage("protection.protected");
}
}
}
/**
* Protect item frames, armor stands, etc. Entities that are actually blocks...
* @param e
*/
@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;
}
// Get the attacker
if (e.getDamager() instanceof Player) {
setUser(User.getInstance(e.getDamager())).checkIsland(e, e.getEntity().getLocation(), Flags.BREAK_BLOCKS);
} else if (e.getDamager() instanceof Projectile) {
// Find out who fired the arrow
Projectile p = (Projectile) e.getDamager();
if (p.getShooter() instanceof Player) {
if (!setUser(User.getInstance((Player)p.getShooter())).checkIsland(e, e.getEntity().getLocation(), Flags.BREAK_BLOCKS)) {
e.getEntity().setFireTicks(0);
e.getDamager().remove();
}
}
}
}
public class BreakBlocksListener implements Listener {
}

View File

@ -0,0 +1,51 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Animals;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles breeding protection
* Note - animal protection is done elsewhere.
* @author tastybento
*
*/
public class BreedingListener extends AbstractFlagListener {
/**
* A list of items that cause breeding if a player has them in their hand and they click an animal
* This list may need to be extended with future versions of Minecraft.
*/
private final static List<Material> BREEDING_ITEMS = Arrays.asList(
Material.EGG,
Material.WHEAT,
Material.CARROT_ITEM,
Material.SEEDS);
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractAtEntityEvent e) {
if (e.getRightClicked() != null && e.getRightClicked() instanceof Animals) {
ItemStack inHand = e.getPlayer().getInventory().getItemInMainHand();
if (e.getHand().equals(EquipmentSlot.OFF_HAND)) {
inHand = e.getPlayer().getInventory().getItemInOffHand();
}
if (inHand != null && BREEDING_ITEMS.contains(inHand.getType())) {
checkIsland(e, e.getRightClicked().getLocation(), Flags.BREEDING);
}
}
}
}

View File

@ -0,0 +1,56 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles interaction with beds
* Note - bed protection from breaking or placing is done elsewhere.
* @author tastybento
*
*/
public class BucketListener extends AbstractFlagListener {
/**
* Prevents emptying of buckets
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBucketEmpty(final PlayerBucketEmptyEvent e) {
if (e.getBlockClicked() != null) {
// This is where the water or lava actually will be dumped
Block dumpBlock = e.getBlockClicked().getRelative(e.getBlockFace());
checkIsland(e, dumpBlock.getLocation(), Flags.BUCKET);
}
}
/**
* Prevents collecting of lava, water, milk. If bucket use is denied in general, it is blocked.
* @param e
*/
@EventHandler(priority = EventPriority.LOW)
public void onBucketFill(final PlayerBucketFillEvent e) {
// Check filling of various liquids
if (e.getItemStack().getType().equals(Material.LAVA_BUCKET) && (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_LAVA))) {
return;
}
if (e.getItemStack().getType().equals(Material.WATER_BUCKET) && (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.COLLECT_WATER))) {
return;
}
if (e.getItemStack().getType().equals(Material.MILK_BUCKET) && (!checkIsland(e, e.getBlockClicked().getLocation(), Flags.MILKING))) {
return;
}
// Check general bucket use
checkIsland(e, e.getBlockClicked().getLocation(), Flags.BUCKET);
}
}

View File

@ -0,0 +1,30 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerEggThrowEvent;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles throwing regular eggs (not spawn eggs)
* @author tastybento
*
*/
public class EggListener extends AbstractFlagListener {
/**
* Handle visitor chicken egg throwing
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEggThrow(PlayerEggThrowEvent e) {
if (!checkIsland(e, e.getEgg().getLocation(), Flags.EGGS)) {
e.setHatching(false);
}
}
}

View File

@ -0,0 +1,43 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.entity.Animals;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles interaction with entities like armor stands
* Note - armor stand protection from breaking or placing is done elsewhere.
* @author tastybento
*
*/
public class EntityInteractListener extends AbstractFlagListener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onPlayerInteract(final PlayerInteractAtEntityEvent e) {
if (e.getRightClicked() instanceof ArmorStand) {
checkIsland(e, e.getRightClicked().getLocation(), Flags.ARMOR_STAND);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerHitEntity(PlayerInteractEntityEvent e) {
// Animal riding
if (e.getRightClicked() instanceof Vehicle && e.getRightClicked() instanceof Animals) {
checkIsland(e, e.getRightClicked().getLocation(), Flags.RIDING);
}
// Villager trading
if (e.getRightClicked().getType().equals(EntityType.VILLAGER)) {
checkIsland(e, e.getRightClicked().getLocation(), Flags.TRADING);
}
}
}

View File

@ -0,0 +1,182 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import java.util.Optional;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.util.BlockIterator;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.database.objects.Island;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles fire
* @author tastybento
*
*/
public class FireListener extends AbstractFlagListener {
/**
* Prevents fire spread
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent e) {
if (!inWorld(e.getBlock().getLocation())) {
return;
}
// 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 not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) {
e.setCancelled(true);
}
}
/**
* Prevent fire spread
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent e) {
if (e.getSource().getType().equals(Material.FIRE)) {
if (!inWorld(e.getBlock().getLocation())) {
return;
}
// 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 not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE_SPREAD.isDefaultSetting()) {
e.setCancelled(true);
}
}
}
/**
* Igniting fires
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent e) {
if (!inWorld(e.getBlock().getLocation())) {
return;
}
// Check if this is a portal lighting - that is allowed any time
if (e.getBlock().getType().equals(Material.OBSIDIAN)) {
return;
}
// 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 not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) {
e.setCancelled(true);
}
}
/**
* Flint & Steel and Extinguishing fire
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) && e.getMaterial() != null && e.getMaterial().equals(Material.FLINT_AND_STEEL)) {
checkIsland(e, e.getClickedBlock().getLocation(), Flags.FIRE);
}
// Look along player's sight line to see if any blocks are fire. Players can hit fire out quite a long way away.
try {
BlockIterator iter = new BlockIterator(e.getPlayer(), 10);
Block lastBlock = iter.next();
while (iter.hasNext()) {
lastBlock = iter.next();
if (lastBlock.equals(e.getClickedBlock())) {
break;
}
if (lastBlock.getType().equals(Material.FIRE)) {
checkIsland(e, lastBlock.getLocation(), Flags.FIRE_EXTINGUISH);
}
}
} catch (Exception ex) {
// To catch at block iterator exceptions that can happen in the void or at the very top of blocks
}
}
/**
* Protect TNT.
* Note that allowing TNT to explode is governed by the Break Blocks flag.
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onTNTPrimed(EntityChangeBlockEvent e) {
// Check world
if (!inWorld(e.getBlock().getLocation())) {
return;
}
// Check for TNT
if (!e.getBlock().getType().equals(Material.TNT)) {
//plugin.getLogger().info("DEBUG: not tnt");
return;
}
// 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 not on an island, check the default setting
if (!island.isPresent() && !Flags.FIRE.isDefaultSetting()) {
e.setCancelled(true);
}
// If either of these canceled the event, 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) {
Projectile projectile = (Projectile) e.getEntity();
// Find out who fired it
if (projectile.getShooter() instanceof Player) {
if (projectile.getFireTicks() > 0) {
Player shooter = (Player)projectile.getShooter();
if (setUser(User.getInstance(shooter)).checkIsland(e, e.getBlock().getLocation(), Flags.BREAK_BLOCKS)) {
// Remove the arrow
projectile.remove();
}
}
}
}
}
}

View File

@ -0,0 +1,201 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Snowman;
import org.bukkit.entity.Squid;
import org.bukkit.entity.Villager;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.potion.PotionEffect;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.api.flags.Flag;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles hurting of monsters and animals directly and indirectly
* @author tastybento
*
*/
public class HurtingListener extends AbstractFlagListener {
private HashMap<Integer, UUID> thrownPotions = new HashMap<>();
/**
* Handles mob and monster protection
*
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamage(final EntityDamageByEntityEvent e) {
// Mobs being hurt
if (e.getEntity() instanceof Animals || e.getEntity() instanceof IronGolem || e.getEntity() instanceof Snowman
|| e.getEntity() instanceof Villager) {
respond(e, e.getDamager(), Flags.HURT_MOBS);
} else if (e.getEntity() instanceof Monster || e.getEntity() instanceof Squid || e.getEntity() instanceof Slime) {
respond(e, e.getDamager(), Flags.HURT_MONSTERS);
}
}
/**
* Finds the true attacker, even if the attack was via a projectile
* @param event
* @param damager
* @param hurtMobs
*/
private void respond(Event event, Entity damager, Flag hurtMobs) {
// Get the attacker
if (damager instanceof Player) {
setUser(User.getInstance(damager)).checkIsland(event, damager.getLocation(), hurtMobs);
} else if (damager instanceof Projectile) {
// Find out who fired the projectile
Projectile p = (Projectile) damager;
if (p.getShooter() instanceof Player) {
if (!setUser(User.getInstance((Player)p.getShooter())).checkIsland(event, damager.getLocation(), hurtMobs)) {
damager.setFireTicks(0);
damager.remove();
}
}
}
}
/**
* Handle attacks with a fishing rod
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onFishing(PlayerFishEvent e) {
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)) {
e.getHook().remove();
return;
}
if ((e.getCaught() instanceof Monster || e.getCaught() instanceof Squid || e.getCaught() instanceof Slime)
&& checkIsland(e, e.getCaught().getLocation(), Flags.HURT_MONSTERS)) {
e.getHook().remove();
return;
}
}
/**
* Handles feeding cookies to animals, which may hurt them
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerHitEntity(PlayerInteractEntityEvent e) {
if (e.getRightClicked() instanceof Animals) {
if ((e.getHand().equals(EquipmentSlot.HAND) && e.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.COOKIE))
|| (e.getHand().equals(EquipmentSlot.OFF_HAND) && e.getPlayer().getInventory().getItemInOffHand().getType().equals(Material.COOKIE))) {
checkIsland(e, e.getRightClicked().getLocation(), Flags.HURT_MOBS);
}
}
}
/**
* Checks for splash damage. Remove damage if it should not affect.
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onSplashPotionSplash(final PotionSplashEvent e) {
// Try to get the shooter
Projectile projectile = e.getEntity();
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
Player attacker = (Player)projectile.getShooter();
// Run through all the affected entities
for (LivingEntity entity: e.getAffectedEntities()) {
// Self damage
if (attacker.equals(entity)) {
continue;
}
// Monsters being hurt
if (entity instanceof Monster || entity instanceof Slime || entity instanceof Squid) {
if (!setUser(User.getInstance(attacker)).checkIsland(e, entity.getLocation(), Flags.HURT_MONSTERS)) {
for (PotionEffect effect : e.getPotion().getEffects()) {
entity.removePotionEffect(effect.getType());
}
}
}
// Mobs being hurt
if (entity instanceof Animals || entity instanceof IronGolem || entity instanceof Snowman
|| entity instanceof Villager) {
if (!checkIsland(e, entity.getLocation(), Flags.HURT_MONSTERS)) {
for (PotionEffect effect : e.getPotion().getEffects()) {
entity.removePotionEffect(effect.getType());
}
}
}
}
}
}
/**
* Handle lingering potions. This tracks when a potion has been initially splashed.
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionSplash(final LingeringPotionSplashEvent e) {
// Try to get the shooter
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
thrownPotions.put(e.getAreaEffectCloud().getEntityId(), uuid);
getPlugin().getServer().getScheduler().runTaskLater(getPlugin(), () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration());
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onLingeringPotionDamage(final EntityDamageByEntityEvent e) {
if (e.getEntity() == null || e.getEntity().getUniqueId() == null) {
return;
}
if (e.getCause().equals(DamageCause.ENTITY_ATTACK) && thrownPotions.containsKey(e.getDamager().getEntityId())) {
UUID attacker = thrownPotions.get(e.getDamager().getEntityId());
// Self damage
if (attacker.equals(e.getEntity().getUniqueId())) {
return;
}
Entity entity = e.getEntity();
// Monsters being hurt
if (entity instanceof Monster || entity instanceof Slime || entity instanceof Squid) {
checkIsland(e, entity.getLocation(), Flags.HURT_MONSTERS);
}
// Mobs being hurt
if (entity instanceof Animals || entity instanceof IronGolem || entity instanceof Snowman
|| entity instanceof Villager) {
checkIsland(e, entity.getLocation(), Flags.HURT_MONSTERS);
}
}
}
}

View File

@ -0,0 +1,60 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.block.Beacon;
import org.bukkit.block.BrewingStand;
import org.bukkit.block.Chest;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Dropper;
import org.bukkit.block.Furnace;
import org.bukkit.block.Hopper;
import org.bukkit.block.ShulkerBox;
import org.bukkit.entity.Animals;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.InventoryClickEvent;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.lists.Flags;
/**
* Handles inventory protection
* @author tastybento
*
*/
public class InventoryListener extends AbstractFlagListener {
/**
* Prevents visitors picking items from inventories
* @param e
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
public void onMountInventoryClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() == null) {
return;
}
if (e.getInventory().getHolder() instanceof Animals) {
checkIsland(e, e.getInventory().getLocation(), Flags.MOUNT_INVENTORY);
}
else if (e.getInventory().getHolder() instanceof Chest
|| e.getInventory().getHolder() instanceof Dispenser
|| e.getInventory().getHolder() instanceof Hopper
|| e.getInventory().getHolder() instanceof Dropper
|| e.getInventory().getHolder() instanceof ShulkerBox) {
setUser(User.getInstance(e.getWhoClicked())).checkIsland(e, e.getInventory().getLocation(), Flags.CHEST);
}
else if (e.getInventory().getHolder() instanceof Furnace) {
setUser(User.getInstance(e.getWhoClicked())).checkIsland(e, e.getInventory().getLocation(), Flags.FURNACE);
}
else if (e.getInventory().getHolder() instanceof BrewingStand) {
setUser(User.getInstance(e.getWhoClicked())).checkIsland(e, e.getInventory().getLocation(), Flags.BREWING);
}
else if (e.getInventory().getHolder() instanceof Beacon) {
setUser(User.getInstance(e.getWhoClicked())).checkIsland(e, e.getInventory().getLocation(), Flags.BEACON);
}
}
}

View File

@ -0,0 +1,39 @@
/**
*
*/
package us.tastybento.bskyblock.listeners.flags;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import us.tastybento.bskyblock.api.commands.User;
import us.tastybento.bskyblock.lists.Flags;
/**
* @author tastybento
*
*/
public class ItemDropPickUpListener extends AbstractFlagListener {
/*
* Handle item drop by visitors
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorDrop(PlayerDropItemEvent e) {
checkIsland(e, e.getItemDrop().getLocation(), Flags.ITEM_DROP);
}
/*
* Handle item pickup by visitors
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onVisitorPickup(EntityPickupItemEvent e) {
if (e.getEntity() instanceof Player) {
// Disallow, but don't tell the player an error
setUser(User.getInstance(e.getEntity())).checkIsland(e, e.getItem().getLocation(), Flags.ITEM_PICKUP, true);
}
}
}

Some files were not shown because too many files have changed in this diff Show More