Java tutorial
/* Creative Commons Attribution-NonCommercial 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 Definitions. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. Licensor means the individual(s) or entity(ies) granting rights under this Public License. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 Scope. License grant. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and produce, reproduce, and Share Adapted Material for NonCommercial purposes only. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. Term. The term of this Public License is specified in Section 6(a). Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. Downstream recipients. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). Other rights. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. Patent and trademark rights are not licensed under this Public License. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. Section 3 License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. Attribution. If You Share the Licensed Material (including in modified form), You must: retain the following if it is supplied by the Licensor with the Licensed Material: identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); a copyright notice; a notice that refers to this Public License; a notice that refers to the disclaimer of warranties; a URI or hyperlink to the Licensed Material to the extent reasonably practicable; indicate if You modified the Licensed Material and retain an indication of any previous modifications; and indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 Disclaimer of Warranties and Limitation of Liability. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 Term and Termination. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 Other Terms and Conditions. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 Interpretation. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. */ package net.cubebeaters; // Local imports import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.md_5.bungee.api.ChatColor; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; /** * * This plugin is designed to provide servers with an RPG style friend list. * * @author Systemx86(Benjamin Sykes) * @version 2.1.6 */ public class FriendsList extends JavaPlugin implements Listener { private final String MSG_PREFIX = ChatColor.AQUA + "[" + ChatColor.GREEN + "FriendsList" + ChatColor.AQUA + "] " + ChatColor.GRAY; // Used in delivering output to the caller. private boolean allowGift; // Allow the gift command. private int friendSlot; private Player friend; private HashMap<String, String> requests = new HashMap<>(); @SuppressWarnings("FieldMayBeFinal") private Inventory friendsMenu = Bukkit.createInventory(null, 18, ChatColor.BLACK + "--[" + ChatColor.DARK_GREEN + "Friends List" + ChatColor.BLACK + "]--"); @SuppressWarnings("FieldMayBeFinal") private Inventory customMenu = Bukkit.createInventory(null, 9, ChatColor.BLACK + "--[" + ChatColor.DARK_GREEN + "Friends List" + ChatColor.BLACK + "]--"); /** * * Executes code when the plugin is Enabled on the server. onEnable() is an * inheirited method from JavaPlugin. * */ @Override public void onEnable() { getServer().getPluginManager().registerEvents(this, this); Logger.getLogger("Starting Friends List, Version: 1.0 with Spigot Version: " + Bukkit.getBukkitVersion()); this.saveDefaultConfig(); Logger.getLogger("Done saving default Config.yml"); } /** * * This method executes code when the plugin is Disabled by a means of a * command or a server shut-down. This method is also inheirrited from * JavaPlugin * */ @Override public void onDisable() { Logger.getLogger(ChatColor.YELLOW + "Saving Friends List..."); this.saveConfig(); Logger.getLogger(ChatColor.GREEN + "Friends List Saved!\nPlugin Disabled."); } /** * * This event detects whether a player has joined the server and if so, * sends a message to all their friends notifying them. * * @param e */ @EventHandler public void onPlayerJoin(PlayerJoinEvent e) { Player joiningPlayer = e.getPlayer(); // Player that is joining the server if (this.getConfig().getBoolean("Plugin-Info.Disable-Default-Login-Message")) { e.setJoinMessage(null); } else { e.setJoinMessage(ChatColor.YELLOW + joiningPlayer.getName() + " has joined the server."); } List<String> friendsList = this.getConfig().getStringList(joiningPlayer.getName()); if (!friendsList.isEmpty()) { for (int x = 0; x < friendsList.size(); x++) { @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(friendsList.get(x)); if (Bukkit.getPlayer(friendsList.get(x)) == null) { return; } friend.sendMessage(MSG_PREFIX + ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("Messages.Join")) .replace("$player", joiningPlayer.getName())); } } } /** * * This event listener is used to handle clicking within the FriendsList * Inventory GUI Menu. * * @param event The Inventory Click Event. */ @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player p = (Player) event.getWhoClicked(); // The player that clicked the item ItemStack clicked = event.getCurrentItem(); // The item that was clicked Inventory inventory = event.getInventory(); // The inventory that was clicked in if (inventory.getName().equals(friendsMenu.getName())) { // The inventory is our custom Inventory if (clicked.getType() == Material.GLASS) { // The item that the player clicked is GLASS friendSlot = event.getSlot(); friend = Bukkit .getPlayer(event.getClickedInventory().getItem(friendSlot).getItemMeta().getDisplayName()); event.setCancelled(true); // Make it so the Glass is back in its original spot p.closeInventory(); // Closes there inventory. try { openFriendMenu(p); // Sets up and opens the Custom Friends menu. } catch (UnsupportedEncodingException ex) { p.sendMessage(MSG_PREFIX + "There was an error opening new Inventory Menu!"); } } } if (inventory.getName().equals(customMenu.getName())) { // Second Menu. if (clicked.getType() == Material.CACTUS) { event.setCancelled(true); p.closeInventory(); try { guiTeleport(p, friend); } catch (UnsupportedEncodingException ex) { p.sendMessage(MSG_PREFIX + "There was an error teleporting you to friends Location."); Logger.getLogger("There was an error telporting " + p.getName()); Logger.getLogger(ex.toString()); } } else if (clicked.getType() == Material.GRASS) { event.setCancelled(true); p.closeInventory(); try { guiGift(p, friend); } catch (UnsupportedEncodingException ex) { p.sendMessage(MSG_PREFIX + "There was an error sending a gift to your friend."); Logger.getLogger("There was an error sending a gift from " + p.getName()); Logger.getLogger(ex.toString()); } } else if (clicked.getType() == Material.BEDROCK) { event.setCancelled(true); p.closeInventory(); try { guiDelFriend(p, friend); } catch (UnsupportedEncodingException ex) { p.sendMessage(MSG_PREFIX + "There was an error removing your friend from your friends list."); Logger.getLogger("There was an error sending a gift from " + p.getName()); Logger.getLogger(ex.toString()); } } } } /** * * Listens for players leaving the server and notifies all their friends as * they do so. * * @param e */ @EventHandler public void onPlayerLeave(PlayerQuitEvent e) { Player leavingPlayer = e.getPlayer(); if (this.getConfig().getBoolean("Plugin-Info.Disable-Default-Leave-Message")) { e.setQuitMessage(null); } else { e.setQuitMessage(ChatColor.YELLOW + leavingPlayer.getName() + " has left the server."); } List<String> friendsList = this.getConfig().getStringList(leavingPlayer.getName()); if (!friendsList.isEmpty()) { for (int x = 0; x < friendsList.size(); x++) { @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(friendsList.get(x)); if (Bukkit.getPlayer(friendsList.get(x)) == null) { return; } friend.sendMessage(MSG_PREFIX + ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("Messages.Leave")) .replace("$player", leavingPlayer.getName())); } } } /** * * Overrides onCommand and executes code within' their respective methods * when cmd.getName() is equal to the co-responding command. * * @param sender The player/server entity that enters a command. * @param cmd Command is used to determine which command is entered, if any. * @param label Not sure why this is needed. * @param args User arguments after command is entered (ex: /command * [arguments] in-game * @return false if no correct command is entered. */ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player p = (Player) sender; // Player who issued the command. // Command sender is an instance of a player if (!(sender instanceof Player)) { if (cmd.getName().equalsIgnoreCase("freload")) { try { reloadConfig(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else if (cmd.getName().equalsIgnoreCase("fsave")) { try { saveConfig(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { sender.sendMessage(MSG_PREFIX + "You cannot run these commands as a server. They can only be run as a Player Entity."); return false; } } else { if (cmd.getName().equalsIgnoreCase("friends")) { if (this.getConfig().getBoolean("Plugin-Info.Enable-GUI")) { // is the GUI allowed? if (p.hasPermission("friendslist.gui")) { try { openMainMenu(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing Permissions."); } } else { sender.sendMessage(MSG_PREFIX + "Sorry, the GUI is not enabled on this server."); } } // Check for all commands and call command executor logic. if (cmd.getName().equalsIgnoreCase("friend")) { if (args.length < 1) { p.sendMessage(MSG_PREFIX + "You must enter a command name such as /friend <add/msg/tp/etc.>"); } else { if (args[0].equalsIgnoreCase("add")) { if (p.hasPermission("friendslist.general.add")) { try { addFriend(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing permissions."); } } else if (args[0].equalsIgnoreCase("remove")) { if (p.hasPermission("friendslist.general.del")) { try { delFriend(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing permissions."); } } else if (args[0].equalsIgnoreCase("list")) { if (p.hasPermission("friendslist.general.list")) { try { listFriends(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing Permissions."); } } else if (args[0].equalsIgnoreCase("tp")) { if (p.hasPermission("friendslist.general.tp")) { try { teleportFriend(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing Permissions."); } } else if (args[0].equalsIgnoreCase("gift")) { if (p.hasPermission("friendslist.general.gift")) { try { sendGift(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing Permissions."); } } else if (args[0].equalsIgnoreCase("msg")) { if (p.hasPermission("friendslist.general.msg")) { try { messageFriend(sender, cmd, label, args); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FriendsList.class.getName()).log(Level.SEVERE, null, ex); } } else { p.sendMessage(ChatColor.RED + "Missing Permissions"); } } else if (args[0].equalsIgnoreCase("accept")) { if (p.hasPermission("friendslist.general.accept")) { acceptRequest(sender, cmd, label, args); } else { p.sendMessage(ChatColor.RED + "Missing Permissions"); } } else if (args[0].equalsIgnoreCase("deny")) { if (p.hasPermission("friendslist.general.deny")) { denyRequest(sender, cmd, label, args); } else { p.sendMessage(ChatColor.RED + "Missing Permissions"); } } else if (args[0].equalsIgnoreCase("help")) { if (p.hasPermission("friendslist.general.help")) { p.sendMessage(MSG_PREFIX + "Commands:"); p.sendMessage( ChatColor.GOLD + "/friend add <Player> - Sends a friend request to <player>"); p.sendMessage(ChatColor.GOLD + "/friend remove <Player> - Removes a friend from your friends list."); p.sendMessage(ChatColor.GOLD + "/friend list - Lists all your current friends"); p.sendMessage( ChatColor.GOLD + "/friend tp <Friend> - Teleports you to <Friend>'s location"); p.sendMessage(ChatColor.GOLD + "/friend gift <Friend> - Gifts the item you're holding to your friend."); p.sendMessage(ChatColor.GOLD + "/friend msg <Friend> <Message> - Sends a private message to <Friend>."); p.sendMessage(ChatColor.GOLD + "/friend accept <Player> - Accepts <Player>'s Friend request."); p.sendMessage( ChatColor.GOLD + "/friend deny <Player> - Denies <Player>'s Friend request."); } else { p.sendMessage(ChatColor.RED + "Missing Permissions (friendslist.general.help)"); } } else { p.sendMessage(MSG_PREFIX + "No recognized command was entered. Please type /friend help to get a full list of available commands."); } } } } return true; } /** * * Adds friend to config.yml under the p.getName() section of the * configuration file allowing the person to interact with the other in many * new ways... * * @param sender * @param cmd * @param label * @param args * @throws UnsupportedEncodingException for file "config.yml" UTF-8 Encoding * error. */ public void addFriend(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (args.length != 2) { p.sendMessage(MSG_PREFIX + "Please enter the command in this format: /friend add <playerToAdd>"); Logger.getLogger(p.getName() + " incorrectly entered a command: /friend add"); } else { // if Config contains playersName section then do not create section... if (this.getConfig().get(p.getName()) == null) { this.getConfig().createSection(p.getName()); } if (this.getConfig().get(args[1]) == null) { this.getConfig().createSection(args[1]); } @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(args[1]); // Friend HumanPlayer Entity. List<String> friendsList = this.getConfig().getStringList(p.getName()); // Gets the list of friends under <PlayerName> if (!friendsList.contains(args[1])) { // if friend is not already a "friend". if (!(args[1].equalsIgnoreCase(p.getName()))) { requests.put(args[1], p.getName()); p.sendMessage(MSG_PREFIX + "A request has been sent to " + args[1]); if (Bukkit.getPlayer(args[1]) != null) { friend.sendMessage(MSG_PREFIX + "You have received a request from " + p.getName() + " type /friend accept <FriendName> or /friend deny <FriendName>"); } } else { p.sendMessage(MSG_PREFIX + "You can't add yourself, silly!"); } } else { // Friend is already on your friends list. p.sendMessage(MSG_PREFIX + args[0] + " is already on your friends list."); } } } /** * * Deletes friend from config.yml and will not allow you to message that * person anymore or teleport to them. * * @param sender * @param cmd * @param label * @param args * @throws UnsupportedEncodingException if UTF-8 encoding is not used. */ public void delFriend(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (args.length != 2) { p.sendMessage(MSG_PREFIX + "Please enter the command in this format: /friend delete <playerToDel>"); Logger.getLogger(MSG_PREFIX + p.getName() + " incorrectly entered a command: /friend delete"); } else { @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(args[1]); List<String> friendList = this.getConfig().getStringList(p.getName()); // Gets list of friends if (this.getConfig().get(args[1]) == null) { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + " is not on your friends list."); return; } List<String> targetFriendsList = this.getConfig().getStringList(args[1]); // Get friends, friend list.. if (friendList.contains(args[1])) { friendList.remove(args[1]); // Removes target from senders friends list. this.getConfig().set(p.getName(), friendList); // Sets new list with removed friend targetFriendsList.remove(p.getName()); // Removes sender from targets friends list. this.getConfig().set(args[1], targetFriendsList); this.saveConfig(); p.sendMessage(MSG_PREFIX + ChatColor .translateAlternateColorCodes('&', this.getConfig().getString("Messages.Removed")) .replace("$friend", args[1])); } else { p.sendMessage(MSG_PREFIX + "Player, " + args[1] + " is not on your friendslist." + "\n if you beleive that this is an Error please contact an Administrator."); Logger.getLogger(MSG_PREFIX + "Friend " + args[1] + " does not exist..."); } } } /** * * This method allows the user to see all their friends they currently have * added. * * @param sender * @param cmd * @param label * @param args entered by the player after the command is entered * @throws UnsupportedEncodingException UTF-8 is not used. */ public void listFriends(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (this.getConfig().get(p.getName()) == null || this.getConfig().getStringList(p.getName()) == null) { p.sendMessage(MSG_PREFIX + "Sorry, you currently do not have any friends to list.."); Logger.getLogger(MSG_PREFIX + "No friend list could be retreived for player, " + p.getName()); } else { List<String> friendsList = this.getConfig().getStringList(p.getName()); // Gets list of friends p.sendMessage(MSG_PREFIX + ChatColor.BOLD + "Friends: " + ChatColor.AQUA + friendsList.toString().replaceAll("\\[", "").replaceAll("\\]", "")); // Displays friendsList on player chat } } /** * * This method will, using the Bukkit API, send a private message to a * friend that is currently present on the senders friends list * * @param sender same as callers super-class * @param cmd same as callers super-class * @param label same as callers super-class * @param args same as callers super-class * @throws UnsupportedEncodingException UTF-8 Encoding is not used. */ public void messageFriend(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; final String MSG_FROM = ChatColor.YELLOW + " (" + ChatColor.WHITE + p.getName() + ChatColor.YELLOW + ") : "; if (args.length < 3) { p.sendMessage(MSG_PREFIX + "Proper usage is /friend msg <PlayerName> <Message>"); Logger.getLogger(MSG_PREFIX + "Improper command usage /friend msg by " + p.getName()); } else { if ((this.getConfig().contains(p.getName())) || (this.getConfig().getStringList(p.getName()) != null)) { List<String> friendsList = this.getConfig().getStringList(p.getName()); if (friendsList.contains(args[1])) { String fullMessage = StringUtils.join(args, ' ', 2, args.length); @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(args[1]); if (Bukkit.getPlayer(args[1]) != null) { // if player is online. if (!(friend.getName().equalsIgnoreCase(p.getName()))) { friend.sendMessage(MSG_PREFIX + MSG_FROM + fullMessage); p.sendMessage( MSG_PREFIX + ChatColor.GREEN + "Message sent to " + ChatColor.BOLD + args[1]); } else { p.sendMessage(MSG_PREFIX + "You can't message yourself, silly!"); } } else { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + " is not online."); } } else { p.sendMessage(MSG_PREFIX + "Sorry, it seems that the person you are trying to message is not a friend."); Logger.getLogger(MSG_PREFIX + "No friends list was found for " + p.getName()); } } else { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + "was not found in your friends list..."); } } } /** * * This method Teleports the sender of the command /ftp [PlayerName] if * [PlayerName] is on the senders friend list. * * @param sender same as callers super-class * @param cmd same as callers super-class * @param label same as callers super-class * @param args same as callers super-class * @throws UnsupportedEncodingException if UTF-8 Encoding is not used */ public void teleportFriend(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (args.length != 2) { p.sendMessage(MSG_PREFIX + "Incorrect Command usage. /friend tp <PlayerName> is the correct usage."); Logger.getLogger(MSG_PREFIX + p.getName() + "Entered a command incorrectly"); } else { if ((this.getConfig().contains(p.getName())) || (this.getConfig().getStringList(p.getName()) != null)) { List<String> friendsList = this.getConfig().getStringList(p.getName()); if (friendsList.contains(args[1])) { @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(args[1]); if (Bukkit.getPlayer(args[1]) != null) { Location friendLocation = friend.getLocation(); p.teleport(friendLocation); p.sendMessage(MSG_PREFIX + "Teleported to " + args[1]); friend.sendMessage(MSG_PREFIX + p.getName() + " Teleported to you!"); } else { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + " is not online.."); } } else { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + " is not your friend!"); } } } } /** * * This method returns to the user all plugin info associated with * FriendsList. * * @param sender The issuer of the command * @param cmd The command that is being issued. * @param label Alais of the command * @param args Arguments to be passed by the commandExecutor. * @throws UnsupportedEncodingException If UTF-8 Encoding is not used. */ public void getPluginInfo(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (this.getConfig().get("Plugin-Info") == null) { this.saveDefaultConfig(); } else { String desc = this.getConfig().getString("Plugin-Info.Description"); p.sendMessage(ChatColor.GOLD + " FriendsList"); // Plugin Title. p.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.GRAY + getDescription().getVersion()); // Plugin Version p.sendMessage(ChatColor.GOLD + "Description: " + ChatColor.GRAY + desc); // Only get from config for fun... p.sendMessage(ChatColor.AQUA + " Plugin by: Ben (Bananna [spigot])"); // Displays plugin creator (Me) } } /** * * Reloads the configuration.yml file in the plugins folder. * * @param sender same as callers super-class. * @param cmd same as callers super-class. * @param label same as callers super-class. * @param args same as callers super-class. * @throws UnsupportedEncodingException if UTF-8 Encoding is not used */ public void reloadConfig(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { if (this.getConfig() != null) { this.reloadConfig(); sender.sendMessage(MSG_PREFIX + "config.yml has been reloaded."); } else { this.saveDefaultConfig(); sender.sendMessage(MSG_PREFIX + "No config.yml file was found. Created one for you!"); } } /** * * Saves the current configuration file in its current state. * * @param sender same as callers super-class. * @param cmd same as callers super-class. * @param label same as callers super-class. * @param args same as callers super-class. * @throws UnsupportedEncodingException if UTF-8 Encoding is not used. */ public void saveConfig(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { if (this.getConfig() != null) { this.saveConfig(); sender.sendMessage(MSG_PREFIX + "config.yml has been saved."); } else { this.saveDefaultConfig(); sender.sendMessage(MSG_PREFIX + "No config.yml file was found. Created one for you!"); } } /** * * Sends a gift to the specified user if he/she is a friend listed in this * plugin. * * @param sender Entity calling the command * @param cmd Command being called * @param label Alais (if Any) * @param args arguments to be passed by the method. * @throws UnsupportedEncodingException if UTF-8 Encoding is not used. */ public void sendGift(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; allowGift = this.getConfig().getBoolean("Plugin-Info.Allow-Gifting"); if (allowGift) { if (args.length < 2) { p.sendMessage(MSG_PREFIX + "Incorrect Command usage. /fgift <PlayerName> <GiftMessage> is the correct usage."); Logger.getLogger(MSG_PREFIX + "Incorrect command usage by player, " + p.getName()); } else { if (this.getConfig().getStringList(p.getName()).contains(args[1])) { ItemStack senderItem = p.getInventory().getItemInHand(); if (Bukkit.getPlayer(args[1]) == null) { p.sendMessage(MSG_PREFIX + "Sorry, " + args[1] + " is not currently online."); } else { @SuppressWarnings("LocalVariableHidesMemberVariable") Player friend = Bukkit.getPlayer(args[1]); PlayerInventory friendInventory = friend.getInventory(); if (senderItem.getType().equals(Material.AIR)) { p.sendMessage(MSG_PREFIX + "You must add an item to your hand, in order to send it to your friend."); } else { friendInventory.addItem(senderItem); p.setItemInHand(new ItemStack(Material.AIR)); // Remove Item from players inventory p.sendMessage(MSG_PREFIX + "Your item has been sent!"); friend.sendMessage(MSG_PREFIX + "You have recieved a gift from " + p.getName() + ". You can thank him later :)"); if (args.length >= 3) { String giftMessage = Arrays.toString(args).replaceAll("\\[", "") .replaceAll("\\]", "").replace(args[1], "").replace(args[0], ""); friend.sendMessage(MSG_PREFIX + ChatColor.BOLD + "Gift Message: " + ChatColor.AQUA + giftMessage); } } } } else { p.sendMessage(MSG_PREFIX + "It appears that " + args[1] + " is not your friend."); } } } else { p.sendMessage(MSG_PREFIX + "Sorry, this option is not enabled in the config.yml"); Logger.getLogger( MSG_PREFIX + "Player, " + p.getName() + " attempted to use /fgift when it is not enabled."); } } /** * * This method sets up and opens the inventory of the player entering * /friends. * * @param player The player who clicked the item that lead to the opening of * this menu * @throws UnsupportedEncodingException if UTF-8 Encoding is not used. */ public void openFriendMenu(Player player) throws UnsupportedEncodingException { Player p = player; List<String> friendsList = this.getConfig().getStringList(p.getName()); createDisplay(Material.CACTUS, customMenu, 1, ChatColor.GREEN + "TP: To Friend", ChatColor.AQUA + "Click to Teleport."); createDisplay(Material.GRASS, customMenu, 3, ChatColor.GOLD + "Gift: Item in Hand", ChatColor.AQUA + "Click to send the item in your hand as a gift."); createDisplay(Material.BEDROCK, customMenu, 6, ChatColor.GOLD + "Delete friend", ChatColor.AQUA + "Click to Remove this friend from your friends List."); p.openInventory(customMenu); // Open inventory... } /** * * This method sets up and opens the inventory of the player entering * /friends. * * @param sender Entity calling the command * @param cmd Command being called * @param label Alais (if Any) * @param args Arguments to be passed (if any) * @throws UnsupportedEncodingException if UTF-8 Encoding is not used. */ public void openMainMenu(CommandSender sender, Command cmd, String label, String[] args) throws UnsupportedEncodingException { Player p = (Player) sender; if (args.length > 0) { p.sendMessage(MSG_PREFIX + "Incorrect Command usage. /friends is the correct usage."); Logger.getLogger(MSG_PREFIX + "Incorrect command usage by player, " + p.getName() + " entering the " + cmd.getName() + " command."); } else { List<String> friendsList = this.getConfig().getStringList(p.getName()); int friendCount = friendsList.size(); for (int x = 0; x < friendCount; x++) { if (Bukkit.getPlayer(friendsList.get(x)) != null) { createDisplay(Material.GLASS, friendsMenu, x, friendsList.get(x), "Click to see options."); } } p.sendMessage(MSG_PREFIX + "Opening Friends List."); p.openInventory(friendsMenu); // Open inventory... } } /** * * This method creates a custom item name/item lore in the specified * inventory and inventory slot. * * @param material Material to use when creating inventory Display * @param inv Inventory object to create object in. * @param Slot Slot to place item in. * @param name Display name of item. * @param lore Description of item. */ public static void createDisplay(Material material, Inventory inv, int Slot, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); List<String> Lore = new ArrayList(); Lore.add(lore); meta.setLore(Lore); item.setItemMeta(meta); inv.setItem(Slot, item); } /** * * This method is the same as the teleportFriend method but is used when the * GUI item 'teleport' is clicked. * * @param player The player to be Teleported. * @param friend The player to be Teleported to. * @throws UnsupportedEncodingException if UTF-8 Encoding is not used. */ public void guiTeleport(Player player, Player friend) throws UnsupportedEncodingException { // Error casting to Player.. Player p = player; try { if (Bukkit.getPlayer(friend.getName()) == null) { p.sendMessage(MSG_PREFIX + "Sorry, your friend is not currently online."); } else { p.teleport(friend); p.sendMessage(MSG_PREFIX + "Teleported to " + friend.getName()); friend.sendMessage(MSG_PREFIX + p.getName() + " has teleported to you."); } } catch (NullPointerException ex) { p.sendMessage(MSG_PREFIX + "It seems that friend is currently offline."); Logger.getLogger(ex.toString()); } } /** * * Sends the currently held item by Player (p) to the friend passed in this * methods parameters. This method also includes a funny message along with * every gift. * * @param p The player sending the item. * @param friend The friend receiving the gift(item). * @throws UnsupportedEncodingException If UTF-8 Encoding is not used. */ public void guiGift(Player p, Player friend) throws UnsupportedEncodingException { // Sends item in hand to friend if (allowGift) { try { if (this.getConfig().getStringList(p.getName()).contains(friend.getName())) { ItemStack senderItem = p.getInventory().getItemInHand(); PlayerInventory friendInventory = friend.getInventory(); if (senderItem.getType().equals(Material.AIR)) { p.sendMessage(MSG_PREFIX + "You must add an item to your hand, in order to send it to your friend."); } else { friendInventory.addItem(senderItem); p.setItemInHand(new ItemStack(Material.AIR)); // Remove Item from players inventory p.sendMessage(MSG_PREFIX + "Your item has been sent!"); friend.sendMessage(MSG_PREFIX + "You have recieved a gift from " + p.getName() + ". You can thank him later :)"); } } else { p.sendMessage(MSG_PREFIX + "It appears that player is not your friend."); } } catch (NullPointerException ex) { p.sendMessage(MSG_PREFIX + "Sorry, but your friend is currently offline."); } } else { p.sendMessage(MSG_PREFIX + "Sorry, gifting is not enabled in the config.yml"); } } /** * * This method removes friend(friend) from the callers(Player(p))'s friends * list. * * @param p The player whos friends List is being affected. * @param friend The friend who is being removed from Player(p)'s friends * List. * @throws UnsupportedEncodingException If UTF-8 Encoding is not used. */ @SuppressWarnings("element-type-mismatch") public void guiDelFriend(Player p, Player friend) throws UnsupportedEncodingException { List<String> friendList = this.getConfig().getStringList(p.getName()); // Gets list of friends if (this.getConfig().get(friend.getName()) == null) { p.sendMessage(MSG_PREFIX + "Sorry, that person is not on your friends list."); return; } List<String> targetFriendsList = this.getConfig().getStringList(friend.getName()); // Get friends, friend list.. if (friendList.contains(friend.getName())) { friendList.remove(friend.getName()); // Removes target from senders friends list. this.getConfig().set(p.getName(), friendList); // Sets new list with removed friend targetFriendsList.remove(p.getName()); // Removes sender from targets friends list. this.getConfig().set(friend.getName(), targetFriendsList); this.saveConfig(); p.sendMessage(MSG_PREFIX + ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("Messages.Removed")) .replace("$friend", friend.getName())); } else { p.sendMessage(MSG_PREFIX + "Sorry, that player is not on your friendslist."); Logger.getLogger(MSG_PREFIX + "Friend does not exist..."); } } /** * * This method is used for the end-user to accept an incoming friend * request. * * @param sender Person executing the command * @param cmd The command being executed * @param label Any Alias associated * @param args Extra arguments to be passed into the command */ public void acceptRequest(CommandSender sender, Command cmd, String label, String[] args) { Player p = (Player) sender; if (args.length < 2) { p.sendMessage(MSG_PREFIX + "Incorrect command usage. Proper usage: /friend accept <friendToAccept>"); } else { if (requests.containsKey(p.getName())) { List<String> friendsList = this.getConfig().getStringList(p.getName()); List<String> targetList = this.getConfig().getStringList(requests.get(p.getName())); targetList.add(p.getName()); // Adds Sender to targets friends list. this.getConfig().set(requests.get(p.getName()), targetList); this.saveConfig(); // saves the config.yml file. friendsList.add(args[1]); // Adds target to senders friends list. this.getConfig().set(p.getName(), friendsList); p.sendMessage(MSG_PREFIX + ChatColor.translateAlternateColorCodes('&', this.getConfig().getString("Messages.Added")) .replace("$friend", args[1])); if (Bukkit.getPlayer(args[1]) != null) { Player f = Bukkit.getPlayer(args[1]); f.sendMessage(MSG_PREFIX + p.getName() + " has been added."); } requests.remove(p.getName()); } else { p.sendMessage(MSG_PREFIX + "There are no requests for you."); } } } /** * * This method is used by the end-user to deny an incoming friend request. * * @param sender Person executing the command * @param cmd The command being executed * @param label Any Alias associated * @param args Extra arguments to be passed into the command */ public void denyRequest(CommandSender sender, Command cmd, String label, String[] args) { Player p = (Player) sender; if (args.length < 2) { p.sendMessage(MSG_PREFIX + "Incorrect command usage. Proper usage: /friend accept <friendToAccept>"); } else { if (requests.containsKey(p.getName())) { requests.remove(p.getName()); requests.remove(args[1]); p.sendMessage(MSG_PREFIX + "Request denied."); if (Bukkit.getPlayer(args[1]) != null) { Player f = Bukkit.getPlayer(args[1]); f.sendMessage(MSG_PREFIX + "Your request has been denied."); } } else { p.sendMessage(MSG_PREFIX + "There are no requests for you."); } } } }