Skip to content

Commit

Permalink
Fixed config.yml upgrade and cleaned up project
Browse files Browse the repository at this point in the history
  • Loading branch information
PyvesB committed Dec 22, 2017
1 parent a418b17 commit 418f5d6
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 79 deletions.
86 changes: 29 additions & 57 deletions src/main/java/com/hm/petmaster/PetMaster.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.io.IOException;
import java.util.logging.Level;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
Expand All @@ -12,7 +11,6 @@
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import com.hm.mcshared.file.CommentedYamlConfiguration;
Expand All @@ -26,8 +24,6 @@
import com.hm.petmaster.listener.PlayerInteractListener;
import com.hm.petmaster.listener.PlayerQuitListener;

import net.milkbowl.vault.economy.Economy;

/**
* Whose pet is this? Manage pets and display owners via holograms, action bar or chat messages!
*
Expand All @@ -46,9 +42,6 @@
*/
public class PetMaster extends JavaPlugin implements Listener {

// Used for Vault plugin integration.
private Economy economy;

// Plugin options and various parameters.
private String chatHeader;
private boolean successfulLoad;
Expand Down Expand Up @@ -81,7 +74,7 @@ public void onEnable() {
// Start enabling plugin.
long startTime = System.currentTimeMillis();

this.getLogger().info("Registering listeners...");
getLogger().info("Registering listeners...");

playerInteractListener = new PlayerInteractListener(this);
playerQuitListener = new PlayerQuitListener(this);
Expand All @@ -92,7 +85,6 @@ public void onEnable() {
pm.registerEvents(playerQuitListener, this);

extractParametersFromConfig(true);
setupEconomy();

chatHeader = ChatColor.GRAY + "[" + ChatColor.GOLD + "\u265E" + ChatColor.GRAY + "] ";

Expand All @@ -113,10 +105,10 @@ public void onEnable() {
reloadCommand = new ReloadCommand(this);

if (successfulLoad) {
this.getLogger().info("Plugin successfully enabled and ready to run! Took "
getLogger().info("Plugin successfully enabled and ready to run! Took "
+ (System.currentTimeMillis() - startTime) + "ms.");
} else {
this.getLogger().severe("Error(s) while loading plugin. Please view previous logs for more information.");
getLogger().severe("Error(s) while loading plugin. Please view previous logs for more information.");
}
}

Expand All @@ -128,7 +120,7 @@ public void onEnable() {
public void extractParametersFromConfig(boolean attemptUpdate) {
successfulLoad = true;

this.getLogger().info("Backing up and loading configuration files...");
getLogger().info("Backing up and loading configuration files...");

config = loadAndBackupYamlConfiguration("config.yml");
if (config == null) {
Expand Down Expand Up @@ -165,24 +157,22 @@ private CommentedYamlConfiguration loadAndBackupYamlConfiguration(String fileNam
CommentedYamlConfiguration yamlConfiguration = null;
try {
yamlConfiguration = new CommentedYamlConfiguration(fileName, this);
} catch (IOException e) {
this.getLogger().log(Level.SEVERE, "Error while loading " + fileName + " file: ", e);
successfulLoad = false;
} catch (InvalidConfigurationException e) {
this.getLogger().severe("Error while loading " + fileName + " file, disabling plugin.");
this.getLogger().log(Level.SEVERE,
} catch (IOException | InvalidConfigurationException e) {
getLogger().severe("Error while loading " + fileName + " file, disabling plugin.");
getLogger().log(Level.SEVERE,
"Verify your syntax by visiting yaml-online-parser.appspot.com and using the following logs: ", e);
successfulLoad = false;
this.getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().disablePlugin(this);
}

if (yamlConfiguration != null)
if (yamlConfiguration != null) {
try {
yamlConfiguration.backupConfiguration();
} catch (IOException e) {
this.getLogger().log(Level.SEVERE, "Error while backing up configuration file: ", e);
getLogger().log(Level.SEVERE, "Error while backing up configuration file: ", e);
successfulLoad = false;
}
}
return yamlConfiguration;
}

Expand All @@ -193,31 +183,30 @@ private CommentedYamlConfiguration loadAndBackupYamlConfiguration(String fileNam
private void updateOldConfiguration() {
updatePerformed = false;

updateSetting(lang, "languageFileName", "lang.yml", new String[] { "Name of the language file." });
updateSetting(lang, "checkForUpdate", true,
new String[] { "Check for update on plugin launch and notify when an OP joins the game." });
updateSetting(lang, "changeOwnerPrice", 0,
new String[] { "Price of the /petm setowner command (requires Vault)." });
updateSetting(lang, "displayDog", true, new String[] { "Take dogs into account." });
updateSetting(lang, "displayCat", true, new String[] { "Take cats into account." });
updateSetting(lang, "displayHorse", true, new String[] { "Take horses into account." });
updateSetting(lang, "displayLlama", true, new String[] { "Take llamas into account." });
updateSetting(lang, "displayParrot", true, new String[] { "Take parrots into account." });
updateSetting(lang, "actionBarMessage", false,
new String[] { "Enable or disable action bar messages when right-clicking on a pet." });
updateSetting(lang, "displayToOwner", false,
new String[] { "Enable or disable showing ownership information for a player's own pets." });
updateSetting(lang, "freePetPrice", 0, new String[] { "Price of the /petm free command (requires Vault)." });
updateSetting(config, "languageFileName", "lang.yml", "Name of the language file.");
updateSetting(config, "checkForUpdate", true,
"Check for update on plugin launch and notify when an OP joins the game.");
updateSetting(config, "changeOwnerPrice", 0, "Price of the /petm setowner command (requires Vault).");
updateSetting(config, "displayDog", true, "Take dogs into account.");
updateSetting(config, "displayCat", true, "Take cats into account.");
updateSetting(config, "displayHorse", true, "Take horses into account.");
updateSetting(config, "displayLlama", true, "Take llamas into account.");
updateSetting(config, "displayParrot", true, "Take parrots into account.");
updateSetting(config, "actionBarMessage", false,
"Enable or disable action bar messages when right-clicking on a pet.");
updateSetting(config, "displayToOwner", false,
"Enable or disable showing ownership information for a player's own pets.");
updateSetting(config, "freePetPrice", 0, "Price of the /petm free command (requires Vault).");
updateSetting(config, "showHealth", true,
new String[] { "Show health next to owner in chat and action bar messages (not holograms)." });
"Show health next to owner in chat and action bar messages (not holograms).");

if (updatePerformed) {
// Changes in the configuration: save and do a fresh load.
try {
config.saveConfiguration();
config.loadConfiguration();
} catch (IOException | InvalidConfigurationException e) {
this.getLogger().log(Level.SEVERE, "Error while saving changes to the configuration file: ", e);
getLogger().log(Level.SEVERE, "Error while saving changes to the configuration file: ", e);
successfulLoad = false;
}
}
Expand Down Expand Up @@ -254,7 +243,7 @@ private void updateOldLanguage() {
lang.saveConfiguration();
lang.loadConfiguration();
} catch (IOException | InvalidConfigurationException e) {
this.getLogger().log(Level.SEVERE, "Error while saving changes to the language file: ", e);
getLogger().log(Level.SEVERE, "Error while saving changes to the language file: ", e);
successfulLoad = false;
}
}
Expand All @@ -265,7 +254,7 @@ private void updateOldLanguage() {
*/
@Override
public void onDisable() {
this.getLogger().info("PetMaster has been disabled.");
getLogger().info("PetMaster has been disabled.");
}

/**
Expand Down Expand Up @@ -312,19 +301,6 @@ private void updateSetting(CommentedYamlConfiguration file, String name, Object
}
}

/**
* Tries to retrieve an Economy instance from Vault.
*/
private void setupEconomy() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager()
.getRegistration(Economy.class);
if (rsp != null) {
economy = rsp.getProvider();
}
}
}

public void setSuccessfulLoad(boolean successfulLoad) {
this.successfulLoad = successfulLoad;
}
Expand All @@ -345,10 +321,6 @@ public CommentedYamlConfiguration getPluginLang() {
return lang;
}

public Economy getEconomy() {
return economy;
}

public SetOwnerCommand getSetOwnerCommand() {
return setOwnerCommand;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
*/
public class EnableDisableCommand {

private PetMaster plugin;
private final PetMaster plugin;
private boolean enabled;

public EnableDisableCommand(PetMaster plugin) {
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/com/hm/petmaster/command/HelpCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void getHelp(CommandSender sender) {
"Display various information about the plugin."),
"/petm info", plugin.getPluginLang().getString("petmaster-command-info-hover",
"Some extra info about the plugin and its awesome author!"));

if (sender.hasPermission("petmaster.free")) {
sendJsonClickableHoverableMessage(sender,
plugin.getChatHeader() + ChatColor.GOLD + "/petm free" + ChatColor.GRAY + " > "
Expand Down Expand Up @@ -81,27 +81,27 @@ public void getHelp(CommandSender sender) {
}

/**
* Sends a packet message to the server in order to display a clickable and hoverable message. A suggested command is
* displayed in the chat when clicked on, and an additional help message appears when a command is hovered.
* Sends a packet message to the server in order to display a clickable and hoverable message. A suggested command
* is displayed in the chat when clicked on, and an additional help message appears when a command is hovered.
*
* @param sender
* @param message
* @param command
* @param hover
*/
public void sendJsonClickableHoverableMessage(CommandSender sender, String message, String command, String hover) {
// Build the json format string.
String json = "{\"text\":\"" + message + "\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\""
+ command + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\"" + hover
+ "\",\"color\":\"gold\"}]}}";

// Send clickable and hoverable message if sender is a player and if no exception is caught.
if (sender instanceof Player) {
// Build the json format string.
String json = "{\"text\":\"" + message + "\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\""
+ command + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":[{\"text\":\"" + hover
+ "\",\"color\":\"gold\"}]}}";
try {
PacketSender.sendChatMessagePacket((Player) sender, json);
} catch (Exception ex) {
plugin.getLogger().severe(
"Errors while trying to display clickable and hoverable message in /petm help command. Displaying standard message instead.");
plugin.getLogger()
.severe("Errors while trying to display clickable and hoverable message in /petm help command. "
+ "Displaying standard message instead.");
sender.sendMessage(message);
}
} else {
Expand Down
25 changes: 15 additions & 10 deletions src/main/java/com/hm/petmaster/listener/PlayerInteractListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.scheduler.BukkitRunnable;

import com.gmail.filoghost.holographicdisplays.api.Hologram;
Expand Down Expand Up @@ -47,6 +48,7 @@ public class PlayerInteractListener implements Listener {

private final PetMaster plugin;
private final int version;
private Economy economy;

// Configuration parameters.
private boolean chatMessage;
Expand All @@ -66,6 +68,14 @@ public class PlayerInteractListener implements Listener {
public PlayerInteractListener(PetMaster petMaster) {
this.plugin = petMaster;
version = Integer.parseInt(PackageType.getServerVersion().split("_")[1]);
// Try to retrieve an Economy instance from Vault.
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager()
.getRegistration(Economy.class);
if (rsp != null) {
economy = rsp.getProvider();
}
}
}

public void extractParameters() {
Expand All @@ -78,8 +88,8 @@ public void extractParameters() {
hologramDuration = plugin.getPluginConfig().getInt("hologramDuration", 50);
changeOwnerPrice = plugin.getPluginConfig().getInt("changeOwnerPrice", 0);
freePetPrice = plugin.getPluginConfig().getInt("freePetPrice", 0);
chatMessage = plugin.getPluginConfig().getBoolean("chatMessage", false);
hologramMessage = plugin.getPluginConfig().getBoolean("hologramMessage", true);
chatMessage = plugin.getPluginConfig().getBoolean("chatMessage", true);
hologramMessage = plugin.getPluginConfig().getBoolean("hologramMessage", false);
actionBarMessage = plugin.getPluginConfig().getBoolean("actionBarMessage", true);
showHealth = plugin.getPluginConfig().getBoolean("showHealth", true);

Expand Down Expand Up @@ -191,6 +201,7 @@ private void freePet(PlayerInteractEntityEvent event, AnimalTamer oldOwner) {
* @param event
* @param owner
*/
@SuppressWarnings("deprecation")
private void displayHologramAndMessage(PlayerInteractEntityEvent event, AnimalTamer owner) {
if (hologramMessage) {
Entity clickedAnimal = event.getRightClicked();
Expand Down Expand Up @@ -245,7 +256,6 @@ public void run() {
if (showHealth) {
Animals damageable = (Animals) event.getRightClicked();
String currentHealth = String.format("%.1f", damageable.getHealth());
@SuppressWarnings("deprecation")
String maxHealth = version < 9 ? String.format("%.1f", damageable.getMaxHealth())
: String.format("%.1f", damageable.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
healthInfo = ChatColor.GRAY + ". " + plugin.getPluginLang().getString("petmaster-health", "Health: ")
Expand Down Expand Up @@ -278,16 +288,11 @@ public void run() {
* @return true if money should be withdrawn from the player, false otherwise
*/
private boolean chargePrice(Player player, int price) {
Economy economy = plugin.getEconomy();
// Charge player for changing ownership.
if (price > 0 && !player.hasPermission("petmaster.admin") && economy != null) {
String priceWithCurrency;
// If server has set different currency names depending on amount, adapt message accordingly.
if (price > 1) {
priceWithCurrency = price + " " + economy.currencyNamePlural();
} else {
priceWithCurrency = price + " " + economy.currencyNameSingular();
}
String priceWithCurrency = price + " "
+ (price > 1 ? economy.currencyNamePlural() : economy.currencyNameSingular());
if (economy.getBalance(player) < price) {
player.sendMessage(plugin.getChatHeader() + ChatColor.translateAlternateColorCodes('&',
plugin.getPluginLang()
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
chatMessage: false

# Enable or disable hologram messages when right-clicking on a pet (requires Holographic Displays).
hologramMessage: true
hologramMessage: false

# Enable or disable action bar messages when right-clicking on a pet.
actionBarMessage: true
Expand Down

0 comments on commit 418f5d6

Please sign in to comment.