diff --git a/src/main/java/org/anjocaido/groupmanager/GMConfiguration.java b/src/main/java/org/anjocaido/groupmanager/GMConfiguration.java index 1a51112..65a0fbc 100644 --- a/src/main/java/org/anjocaido/groupmanager/GMConfiguration.java +++ b/src/main/java/org/anjocaido/groupmanager/GMConfiguration.java @@ -17,11 +17,10 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.reader.UnicodeReader; /** - * + * * @author gabrielcouto */ public class GMConfiguration { - private boolean allowCommandBlocks = false; private boolean opOverride = true; private boolean toggleValidate = true; @@ -29,14 +28,11 @@ public class GMConfiguration { private Integer backupDuration = 24; private String loggerLevel = "OFF"; private Map mirrorsMap; - - private GroupManager plugin; + private final GroupManager plugin; private Map GMconfig; - public GMConfiguration(GroupManager plugin) { - + public GMConfiguration(final GroupManager plugin) { this.plugin = plugin; - /* * Set defaults */ @@ -46,102 +42,118 @@ public class GMConfiguration { saveInterval = 10; backupDuration = 24; loggerLevel = "OFF"; - load(); } + public void adjustLoggerLevel() { + try { + GroupManager.logger.setLevel(Level.parse(loggerLevel)); + return; + } catch (final Exception e) { + } + GroupManager.logger.setLevel(Level.INFO); + } + + public Integer getBackupDuration() { + return backupDuration; + } + + public Map getMirrorsMap() { + if (!mirrorsMap.isEmpty()) { + return mirrorsMap; + } + return null; + } + + public Integer getSaveInterval() { + return saveInterval; + } + + public boolean isAllowCommandBlocks() { + return allowCommandBlocks; + } + + public boolean isOpOverride() { + return opOverride; + } + + public boolean isToggleValidate() { + return toggleValidate; + } + @SuppressWarnings("unchecked") public void load() { - if (!plugin.getDataFolder().exists()) { plugin.getDataFolder().mkdirs(); } - - File configFile = new File(plugin.getDataFolder(), "config.yml"); - + final File configFile = new File(plugin.getDataFolder(), "config.yml"); if (!configFile.exists()) { try { Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile); - } catch (IOException ex) { + } catch (final IOException ex) { GroupManager.logger.log(Level.SEVERE, "Error creating a new config.yml", ex); } } - - Yaml configYAML = new Yaml(new SafeConstructor()); - + final Yaml configYAML = new Yaml(new SafeConstructor()); try { - FileInputStream configInputStream = new FileInputStream(configFile); + final FileInputStream configInputStream = new FileInputStream(configFile); GMconfig = (Map) configYAML.load(new UnicodeReader(configInputStream)); configInputStream.close(); - - } catch (Exception ex) { + } catch (final Exception ex) { throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex); } - /* * Read our config settings and store them for reading later. */ try { - Map config = getElement("config", getElement("settings", GMconfig)); - + final Map config = getElement("config", getElement("settings", GMconfig)); try { allowCommandBlocks = (Boolean) config.get("allow_commandblocks"); - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'allow_commandblocks' node. Using default settings", ex); } - try { opOverride = (Boolean) config.get("opOverrides"); - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'opOverrides' node. Using default settings", ex); } - try { toggleValidate = (Boolean) config.get("validate_toggle"); - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'validate_toggle' node. Using default settings", ex); } - /* * data node for save/backup timers. */ try { - Map save = getElement("save", getElement("data", getElement("settings", GMconfig))); - + final Map save = getElement("save", getElement("data", getElement("settings", GMconfig))); try { saveInterval = (Integer) save.get("minutes"); - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'minutes' node. Using default setting", ex); } - try { backupDuration = (Integer) save.get("hours"); - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'hours' node. Using default setting", ex); } - - } catch (Exception ex) { + } catch (final Exception ex) { GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'data' node. Using default settings", ex); } - - Object level = ((Map) getElement("settings", GMconfig).get("logging")).get("level"); + final Object level = ((Map) getElement("settings", GMconfig).get("logging")).get("level"); if (level instanceof String) loggerLevel = (String) level; - /* * Store our mirrors map for parsing later. */ mirrorsMap = (Map) ((Map) GMconfig.get("settings")).get("mirrors"); - if (mirrorsMap == null) throw new Exception(); - - } catch (Exception ex) { + } catch (final Exception ex) { /* * Flag the error and use defaults */ GroupManager.logger.log(Level.SEVERE, "There are errors in your config.yml. Using default settings", ex); - mirrorsMap = new HashMap(); } // Setup defaults @@ -150,59 +162,10 @@ public class GMConfiguration { } @SuppressWarnings("unchecked") - private Map getElement(String element, Map map) { - + private Map getElement(final String element, final Map map) { if (!map.containsKey(element)) { throw new IllegalArgumentException("The config.yml has no '" + element + ".\n"); } - return (Map) map.get(element); - } - - public boolean isAllowCommandBlocks() { - - return allowCommandBlocks; - } - - public boolean isOpOverride() { - - return opOverride; - } - - public boolean isToggleValidate() { - - return toggleValidate; - } - - public Integer getSaveInterval() { - - return saveInterval; - } - - public Integer getBackupDuration() { - - return backupDuration; - } - - public void adjustLoggerLevel() { - - try { - GroupManager.logger.setLevel(Level.parse(loggerLevel)); - return; - } catch (Exception e) { - } - - GroupManager.logger.setLevel(Level.INFO); - } - - public Map getMirrorsMap() { - - if (!mirrorsMap.isEmpty()) { - return mirrorsMap; - } - return null; - - } - } diff --git a/src/main/java/org/anjocaido/groupmanager/GlobalGroups.java b/src/main/java/org/anjocaido/groupmanager/GlobalGroups.java index 6c92046..4312b73 100644 --- a/src/main/java/org/anjocaido/groupmanager/GlobalGroups.java +++ b/src/main/java/org/anjocaido/groupmanager/GlobalGroups.java @@ -25,35 +25,142 @@ import org.yaml.snakeyaml.reader.UnicodeReader; /** * @author ElgarL - * + * */ public class GlobalGroups { - - private GroupManager plugin; + private final GroupManager plugin; // private Yaml GGroups; - private final Map groups = Collections.synchronizedMap(new HashMap()); - protected long timeStampGroups = 0; protected boolean haveGroupsChanged = false; protected File GlobalGroupsFile = null; - public GlobalGroups(GroupManager plugin) { - + public GlobalGroups(final GroupManager plugin) { this.plugin = plugin; load(); } + /** + * Adds a group, or replaces an existing one. + * + * @param groupToAdd + */ + public void addGroup(Group groupToAdd) { + // Create a new group if it already exists + if (hasGroup(groupToAdd.getName())) { + groupToAdd = groupToAdd.clone(); + removeGroup(groupToAdd.getName()); + } + newGroup(groupToAdd); + haveGroupsChanged = true; + if (GroupManager.isLoaded()) + GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED); + } + + /** + * Returns a PermissionCheckResult of the permission node for the group to + * be tested against. + * + * @param groupName + * @param permissionNode + * @return PermissionCheckResult object + */ + public PermissionCheckResult checkPermission(final String groupName, final String permissionNode) { + final PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = permissionNode; + result.resultType = PermissionCheckResult.Type.NOTFOUND; + if (!hasGroup(groupName)) + return result; + final Group tempGroup = groups.get(groupName.toLowerCase()); + if (tempGroup.hasSamePermissionNode(permissionNode)) + result.resultType = PermissionCheckResult.Type.FOUND; + if (tempGroup.hasSamePermissionNode("-" + permissionNode)) + result.resultType = PermissionCheckResult.Type.NEGATION; + if (tempGroup.hasSamePermissionNode("+" + permissionNode)) + result.resultType = PermissionCheckResult.Type.EXCEPTION; + return result; + } + + /** + * @return the globalGroupsFile + */ + public File getGlobalGroupsFile() { + return GlobalGroupsFile; + } + + /** + * Returns the Global Group or null if it doesn't exist. + * + * @param groupName + * @return Group object + */ + public Group getGroup(final String groupName) { + if (!hasGroup(groupName)) + return null; + return groups.get(groupName.toLowerCase()); + } + + /** + * + * @return a collection of the groups + */ + public Group[] getGroupList() { + synchronized (groups) { + return groups.values().toArray(new Group[0]); + } + } + + /** + * Returns a List of all permission nodes for this group null if none + * + * @param groupName + * @return List of all group names + */ + public List getGroupsPermissions(final String groupName) { + if (!hasGroup(groupName)) + return null; + return groups.get(groupName.toLowerCase()).getPermissionList(); + } + + /** + * @return the timeStampGroups + */ + public long getTimeStampGroups() { + return timeStampGroups; + } + + /** + * Returns true if the Global Group exists in the globalgroups.yml + * + * @param groupName + * @return true if the group exists + */ + public boolean hasGroup(final String groupName) { + return groups.containsKey(groupName.toLowerCase()); + } + + /** + * Returns true if the group has the correct permission node. + * + * @param groupName + * @param permissionNode + * @return true if node exists + */ + public boolean hasPermission(final String groupName, final String permissionNode) { + if (!hasGroup(groupName)) + return false; + return groups.get(groupName.toLowerCase()).hasSamePermissionNode(permissionNode); + } + /** * @return the haveGroupsChanged */ public boolean haveGroupsChanged() { - if (this.haveGroupsChanged) { return true; } synchronized (groups) { - for (Group g : groups.values()) { + for (final Group g : groups.values()) { if (g.isChanged()) { return true; } @@ -62,85 +169,48 @@ public class GlobalGroups { return false; } - /** - * @return the timeStampGroups - */ - public long getTimeStampGroups() { - - return timeStampGroups; - } - - /** - * @param timeStampGroups - * the timeStampGroups to set - */ - protected void setTimeStampGroups(long timeStampGroups) { - - this.timeStampGroups = timeStampGroups; - } - - /** - * @param haveGroupsChanged - * the haveGroupsChanged to set - */ - public void setGroupsChanged(boolean haveGroupsChanged) { - - this.haveGroupsChanged = haveGroupsChanged; - } - @SuppressWarnings("unchecked") public void load() { - - Yaml GGroupYAML = new Yaml(new SafeConstructor()); + final Yaml GGroupYAML = new Yaml(new SafeConstructor()); Map GGroups; - GroupManager.setLoaded(false); - // READ globalGroups FILE if (GlobalGroupsFile == null) GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml"); - if (!GlobalGroupsFile.exists()) { try { // Create a new file if it doesn't exist. Tasks.copy(plugin.getResourceAsStream("globalgroups.yml"), GlobalGroupsFile); - } catch (IOException ex) { + } catch (final IOException ex) { GroupManager.logger.log(Level.SEVERE, null, ex); } } - /* * Load the YAML file. */ try { - FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile); + final FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile); GGroups = (Map) GGroupYAML.load(new UnicodeReader(groupsInputStream)); groupsInputStream.close(); - } catch (Exception ex) { - throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + GlobalGroupsFile.getPath(), ex); + } catch (final Exception ex) { + throw new IllegalArgumentException("下列文件无法被解析.\n" + GlobalGroupsFile.getPath(), ex); } - // Clear out old groups resetGlobalGroups(); - if (!GGroups.keySet().isEmpty()) { // Read all global groups Map allGroups = new HashMap(); - try { allGroups = (Map) GGroups.get("groups"); - } catch (Exception ex) { + } catch (final Exception ex) { // ex.printStackTrace(); - throw new IllegalArgumentException("Your " + GlobalGroupsFile.getPath() + " file is invalid. See console for details.", ex); + throw new IllegalArgumentException("你的 " + GlobalGroupsFile.getPath() + " 文件不正确. 请查看控制台错误.", ex); } - // Load each groups permissions list. if (allGroups != null) { - - Iterator groupItr = allGroups.keySet().iterator(); + final Iterator groupItr = allGroups.keySet().iterator(); String groupName; Integer groupCount = 0; - /* * loop each group entry * and read it's data. @@ -150,39 +220,35 @@ public class GlobalGroups { groupCount++; // Attempt to fetch the next group name. groupName = groupItr.next(); - } catch (Exception ex) { + } catch (final Exception ex) { throw new IllegalArgumentException("Invalid group name for GlobalGroup entry (" + groupCount + ") in file: " + GlobalGroupsFile.getPath(), ex); } - /* * Create a new group with this name. */ - Group newGroup = new Group(groupName.toLowerCase()); + final Group newGroup = new Group(groupName.toLowerCase()); Object element; - // Permission nodes try { element = ((Map) allGroups.get(groupName)).get("permissions"); - } catch (Exception ex) { + } catch (final Exception ex) { throw new IllegalArgumentException("The GlobalGroup ' " + groupName + "' is formatted incorrectly: ", ex); } - if (element != null) if (element instanceof List) { try { - for (String node : (List) element) { + for (final String node : (List) element) { if ((node != null) && !node.isEmpty()) newGroup.addPermission(node); } - } catch (ClassCastException ex) { - throw new IllegalArgumentException("Invalid permission node for global group: " + groupName, ex); + } catch (final ClassCastException ex) { + throw new IllegalArgumentException("不注册的权限节点 在全局组: " + groupName, ex); } } else if (element instanceof String) { if ((element != null) && !((String) element).isEmpty()) newGroup.addPermission((String) element); } else - throw new IllegalArgumentException("Unknown type of permission node for global group: " + groupName); - + throw new IllegalArgumentException("未知的权限类型 在全局组: " + groupName); // // Info nodes // try { // element = ((Map)allGroups.get(groupName)).get("info"); @@ -199,42 +265,103 @@ public class GlobalGroups { // newGroup.setVariables(vars); // } else // throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName); - // Push a new group addGroup(newGroup); } } - removeGroupsChangedFlag(); } - setTimeStampGroups(GlobalGroupsFile.lastModified()); GroupManager.setLoaded(true); // GlobalGroupsFile = null; } + /** + * Creates a new group if it doesn't already exist. + * + * @param newGroup + */ + public Group newGroup(final Group newGroup) { + // Push a new group + if (!groups.containsKey(newGroup.getName().toLowerCase())) { + groups.put(newGroup.getName().toLowerCase(), newGroup); + this.setGroupsChanged(true); + return newGroup; + } + return null; + } + + /** + * Delete a group if it exist. + * + * @param groupName + */ + public boolean removeGroup(final String groupName) { + // Push a new group + if (groups.containsKey(groupName.toLowerCase())) { + groups.remove(groupName.toLowerCase()); + this.setGroupsChanged(true); + if (GroupManager.isLoaded()) + GroupManager.getGMEventHandler().callEvent(groupName.toLowerCase(), GMGroupEvent.Action.GROUP_REMOVED); + return true; + } + return false; + } + + /** + * + */ + public void removeGroupsChangedFlag() { + setGroupsChanged(false); + synchronized (groups) { + for (final Group g : groups.values()) { + g.flagAsSaved(); + } + } + } + + /** + * Returns a Set of all global group names. + * + * @return Set containing all group names. + */ + /* + * public Set getGlobalGroups() { + * + * return groups.keySet(); + * } + */ + /** + * Resets GlobalGroups. + */ + public void resetGlobalGroups() { + this.groups.clear(); + } + + /** + * @param haveGroupsChanged + * the haveGroupsChanged to set + */ + public void setGroupsChanged(final boolean haveGroupsChanged) { + this.haveGroupsChanged = haveGroupsChanged; + } + /** * Write the globalgroups.yml file */ - - public void writeGroups(boolean overwrite) { - + public void writeGroups(final boolean overwrite) { // File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml"); - if (haveGroupsChanged()) { if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) { - Map root = new HashMap(); - - Map groupsMap = new HashMap(); + final Map root = new HashMap(); + final Map groupsMap = new HashMap(); root.put("groups", groupsMap); synchronized (groups) { - for (String groupKey : groups.keySet()) { - Group group = groups.get(groupKey); - + for (final String groupKey : groups.keySet()) { + final Group group = groups.get(groupKey); // Group header - Map aGroupMap = new HashMap(); + final Map aGroupMap = new HashMap(); groupsMap.put(group.getName(), aGroupMap); - // // Info nodes // Map infoMap = new HashMap(); // aGroupMap.put("info", infoMap); @@ -242,20 +369,18 @@ public class GlobalGroups { // for (String infoKey : group.getVariables().getVarKeyList()) { // infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); // } - // Permission nodes aGroupMap.put("permissions", group.getPermissionList()); } } - if (!root.isEmpty()) { - DumperOptions opt = new DumperOptions(); + final DumperOptions opt = new DumperOptions(); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); final Yaml yaml = new Yaml(opt); try { yaml.dump(root, new OutputStreamWriter(new FileOutputStream(GlobalGroupsFile), "UTF-8")); - } catch (UnsupportedEncodingException ex) { - } catch (FileNotFoundException ex) { + } catch (final UnsupportedEncodingException ex) { + } catch (final FileNotFoundException ex) { } } setTimeStampGroups(GlobalGroupsFile.lastModified()); @@ -274,210 +399,27 @@ public class GlobalGroups { load(); } } - } /** * Backup the BlobalGroups file - * + * * @param w */ private void backupFile() { - - File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml"); + final File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml"); try { Tasks.copy(GlobalGroupsFile, backupFile); - } catch (IOException ex) { + } catch (final IOException ex) { GroupManager.logger.log(Level.SEVERE, null, ex); } } /** - * Adds a group, or replaces an existing one. - * - * @param groupToAdd + * @param timeStampGroups + * the timeStampGroups to set */ - public void addGroup(Group groupToAdd) { - - // Create a new group if it already exists - if (hasGroup(groupToAdd.getName())) { - groupToAdd = groupToAdd.clone(); - removeGroup(groupToAdd.getName()); - } - - newGroup(groupToAdd); - haveGroupsChanged = true; - if (GroupManager.isLoaded()) - GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED); + protected void setTimeStampGroups(final long timeStampGroups) { + this.timeStampGroups = timeStampGroups; } - - /** - * Creates a new group if it doesn't already exist. - * - * @param newGroup - */ - public Group newGroup(Group newGroup) { - - // Push a new group - if (!groups.containsKey(newGroup.getName().toLowerCase())) { - groups.put(newGroup.getName().toLowerCase(), newGroup); - this.setGroupsChanged(true); - return newGroup; - } - return null; - } - - /** - * Delete a group if it exist. - * - * @param groupName - */ - public boolean removeGroup(String groupName) { - - // Push a new group - if (groups.containsKey(groupName.toLowerCase())) { - groups.remove(groupName.toLowerCase()); - this.setGroupsChanged(true); - if (GroupManager.isLoaded()) - GroupManager.getGMEventHandler().callEvent(groupName.toLowerCase(), GMGroupEvent.Action.GROUP_REMOVED); - return true; - } - return false; - } - - /** - * Returns true if the Global Group exists in the globalgroups.yml - * - * @param groupName - * @return true if the group exists - */ - public boolean hasGroup(String groupName) { - - return groups.containsKey(groupName.toLowerCase()); - } - - /** - * Returns true if the group has the correct permission node. - * - * @param groupName - * @param permissionNode - * @return true if node exists - */ - public boolean hasPermission(String groupName, String permissionNode) { - - if (!hasGroup(groupName)) - return false; - - return groups.get(groupName.toLowerCase()).hasSamePermissionNode(permissionNode); - - } - - /** - * Returns a PermissionCheckResult of the permission node for the group to - * be tested against. - * - * @param groupName - * @param permissionNode - * @return PermissionCheckResult object - */ - public PermissionCheckResult checkPermission(String groupName, String permissionNode) { - - PermissionCheckResult result = new PermissionCheckResult(); - result.askedPermission = permissionNode; - result.resultType = PermissionCheckResult.Type.NOTFOUND; - - if (!hasGroup(groupName)) - return result; - - Group tempGroup = groups.get(groupName.toLowerCase()); - - if (tempGroup.hasSamePermissionNode(permissionNode)) - result.resultType = PermissionCheckResult.Type.FOUND; - if (tempGroup.hasSamePermissionNode("-" + permissionNode)) - result.resultType = PermissionCheckResult.Type.NEGATION; - if (tempGroup.hasSamePermissionNode("+" + permissionNode)) - result.resultType = PermissionCheckResult.Type.EXCEPTION; - - return result; - } - - /** - * Returns a List of all permission nodes for this group null if none - * - * @param groupName - * @return List of all group names - */ - public List getGroupsPermissions(String groupName) { - - if (!hasGroup(groupName)) - return null; - - return groups.get(groupName.toLowerCase()).getPermissionList(); - } - - /** - * Returns a Set of all global group names. - * - * @return Set containing all group names. - */ - /* - * public Set getGlobalGroups() { - * - * return groups.keySet(); - * } - */ - - /** - * Resets GlobalGroups. - */ - public void resetGlobalGroups() { - this.groups.clear(); - } - - /** - * - * @return a collection of the groups - */ - public Group[] getGroupList() { - synchronized (groups) { - return groups.values().toArray(new Group[0]); - } - } - - /** - * Returns the Global Group or null if it doesn't exist. - * - * @param groupName - * @return Group object - */ - public Group getGroup(String groupName) { - - if (!hasGroup(groupName)) - return null; - - return groups.get(groupName.toLowerCase()); - - } - - /** - * @return the globalGroupsFile - */ - public File getGlobalGroupsFile() { - - return GlobalGroupsFile; - } - - /** - * - */ - public void removeGroupsChangedFlag() { - - setGroupsChanged(false); - synchronized (groups) { - for (Group g : groups.values()) { - g.flagAsSaved(); - } - } - } - } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/GroupManager.java b/src/main/java/org/anjocaido/groupmanager/GroupManager.java index 68dd8ee..112827c 100644 --- a/src/main/java/org/anjocaido/groupmanager/GroupManager.java +++ b/src/main/java/org/anjocaido/groupmanager/GroupManager.java @@ -51,7 +51,6 @@ import cn.citycraft.PluginHelper.utils.VersionChecker; * @author gabrielcouto, ElgarL */ public class GroupManager extends JavaPlugin { - private static boolean isLoaded = false; protected static GlobalGroups globalGroups; private static GroupManagerEventHandler GMEventHandler; @@ -59,38 +58,28 @@ public class GroupManager extends JavaPlugin { private static GMWorldListener WorldEvents; public static final Logger logger = Logger.getLogger(GroupManager.class.getName()); private File backupFolder; - private Runnable commiter; private ScheduledThreadPoolExecutor scheduler; - private Map> overloadedUsers = new HashMap>(); - private Map selectedWorlds = new HashMap(); - private WorldsHolder worldsHolder; private boolean validateOnlinePlayer = true; protected GMConfiguration config; private GMLoggerHandler ch; - // PERMISSIONS FOR COMMAND BEING LOADED private OverloadedWorldHolder dataHolder = null; private AnjoPermissionsHandler permissionHandler = null; - private String lastError = ""; public static GlobalGroups getGlobalGroups() { - return globalGroups; - } public static GroupManagerEventHandler getGMEventHandler() { - return GMEventHandler; } public static boolean isLoaded() { - return isLoaded; } @@ -103,9 +92,7 @@ public class GroupManager extends JavaPlugin { * @param msg */ public static void notify(final String name, final String msg) { - final Player player = Bukkit.getServer().getPlayerExact(name); - for (final Player test : Bukkit.getServer().getOnlinePlayers()) { if (!test.equals(player)) { if (test.hasPermission("groupmanager.notify.other")) @@ -113,21 +100,17 @@ public class GroupManager extends JavaPlugin { } else if ((player != null) && ((player.hasPermission("groupmanager.notify.self")) || (player.hasPermission("groupmanager.notify.other")))) player.sendMessage(ChatColor.YELLOW + "You were" + msg); } - } public static void setGMEventHandler(final GroupManagerEventHandler gMEventHandler) { - GMEventHandler = gMEventHandler; } public static void setLoaded(final boolean isLoaded) { - GroupManager.isLoaded = isLoaded; } public void disableScheduler() { - if (scheduler != null) { try { scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); @@ -136,21 +119,19 @@ public class GroupManager extends JavaPlugin { } catch (final Exception e) { } scheduler = null; - GroupManager.logger.info("Scheduled Data Saving is disabled!"); + GroupManager.logger.info("自动保存已关闭!"); } } public void enableScheduler() { - if (worldsHolder != null) { disableScheduler(); commiter = new Runnable() { - @Override public void run() { try { if (worldsHolder.saveChanges(false)) - GroupManager.logger.log(Level.INFO, " Data files refreshed."); + GroupManager.logger.log(Level.INFO, " 数据文件已更新."); } catch (final IllegalStateException ex) { GroupManager.logger.log(Level.WARNING, ex.getMessage()); } @@ -160,11 +141,10 @@ public class GroupManager extends JavaPlugin { final long minutes = getGMConfig().getSaveInterval(); if (minutes > 0) { scheduler.scheduleAtFixedRate(commiter, minutes, minutes, TimeUnit.MINUTES); - GroupManager.logger.info("Scheduled Data Saving is set for every " + minutes + " minutes!"); + GroupManager.logger.info("数据文件将每隔 " + minutes + " 分钟 自动保存!"); } else - GroupManager.logger.info("Scheduled Data Saving is Disabled!"); - - GroupManager.logger.info("Backups will be retained for " + getGMConfig().getBackupDuration() + " hours!"); + GroupManager.logger.info("自动保存已关闭!"); + GroupManager.logger.info("数据文件将自动备份每隔 " + getGMConfig().getBackupDuration() + " 小时!"); } } @@ -172,7 +152,6 @@ public class GroupManager extends JavaPlugin { * @return the backupFolder */ public File getBackupFolder() { - return backupFolder; } @@ -180,17 +159,14 @@ public class GroupManager extends JavaPlugin { * @return the config */ public GMConfiguration getGMConfig() { - return config; } public InputStream getResourceAsStream(final String fileName) { - return this.getClassLoader().getResourceAsStream(fileName); } public WorldsHolder getWorldsHolder() { - return worldsHolder; } @@ -198,7 +174,6 @@ public class GroupManager extends JavaPlugin { * @return the validateOnlinePlayer */ public boolean isValidateOnlinePlayer() { - return validateOnlinePlayer; } @@ -211,7 +186,6 @@ public class GroupManager extends JavaPlugin { */ @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { - boolean playerCanDo = false; boolean isConsole = false; Player senderPlayer = null, targetPlayer = null; @@ -219,7 +193,6 @@ public class GroupManager extends JavaPlugin { User senderUser = null; boolean isOpOverride = config.isOpOverride(); final boolean isAllowCommandBlocks = config.isAllowCommandBlocks(); - // PREVENT GM COMMANDS BEING USED ON COMMANDBLOCKS if (sender instanceof BlockCommandSender && !isAllowCommandBlocks) { final Block block = ((BlockCommandSender) sender).getBlock(); @@ -227,54 +200,42 @@ public class GroupManager extends JavaPlugin { GroupManager.logger.warning(ChatColor.RED + "Location: " + ChatColor.GREEN + block.getWorld().getName() + ", " + block.getX() + ", " + block.getY() + ", " + block.getZ()); return true; } - // DETERMINING PLAYER INFORMATION if (sender instanceof Player) { senderPlayer = (Player) sender; - if (!lastError.isEmpty() && !commandLabel.equalsIgnoreCase("manload")) { sender.sendMessage(ChatColor.RED + "All commands are locked due to an error. " + ChatColor.BOLD + "" + ChatColor.UNDERLINE + "Check plugins/groupmanager/error.log or console" + ChatColor.RESET + "" + ChatColor.RED + " and then try a '/manload'."); return true; } - senderUser = worldsHolder.getWorldData(senderPlayer).getUser(senderPlayer.getName()); senderGroup = senderUser.getGroup(); isOpOverride = (isOpOverride && (senderPlayer.isOp() || worldsHolder.getWorldPermissions(senderPlayer).has(senderPlayer, "groupmanager.op"))); - if (isOpOverride || worldsHolder.getWorldPermissions(senderPlayer).has(senderPlayer, "groupmanager." + cmd.getName())) { playerCanDo = true; } } else { - if (!lastError.isEmpty() && !commandLabel.equalsIgnoreCase("manload")) { sender.sendMessage(ChatColor.RED + "All commands are locked due to an error. " + ChatColor.BOLD + "" + ChatColor.UNDERLINE + "Check plugins/groupmanager/error.log or console" + ChatColor.RESET + "" + ChatColor.RED + " and then try a '/manload'."); return true; } - isConsole = true; } - // PERMISSIONS FOR COMMAND BEING LOADED dataHolder = null; permissionHandler = null; - if (senderPlayer != null) { dataHolder = worldsHolder.getWorldData(senderPlayer); } - final String selectedWorld = selectedWorlds.get(sender.getName()); if (selectedWorld != null) { dataHolder = worldsHolder.getWorldData(selectedWorld); } - if (dataHolder != null) { permissionHandler = dataHolder.getPermissionsHandler(); } - // VARIABLES USED IN COMMANDS - int count; PermissionCheckResult permissionResult = null; ArrayList removeList = null; @@ -283,14 +244,13 @@ public class GroupManager extends JavaPlugin { User auxUser = null; Group auxGroup = null; Group auxGroup2 = null; - GroupManagerPermissions execCmd = null; try { execCmd = GroupManagerPermissions.valueOf(cmd.getName()); } catch (final Exception e) { // this error happened once with someone. now im prepared... i think GroupManager.logger.severe("==================================================="); - GroupManager.logger.severe("= ERROR REPORT START ="); + GroupManager.logger.severe("= 错误报告 开始 ="); GroupManager.logger.severe("==================================================="); GroupManager.logger.severe("= COPY AND PASTE THIS TO A GROUPMANAGER DEVELOPER ="); GroupManager.logger.severe("==================================================="); @@ -309,37 +269,31 @@ public class GroupManager extends JavaPlugin { GroupManager.logger.severe(val.name()); } GroupManager.logger.severe("==================================================="); - GroupManager.logger.severe("= ERROR REPORT ENDED ="); + GroupManager.logger.severe("= 错误报告 结束 ="); GroupManager.logger.severe("==================================================="); sender.sendMessage("An error occurred. Ask the admin to take a look at the console."); } - if (isConsole || playerCanDo) { switch (execCmd) { case manuadd: - // Validating arguments if ((args.length != 2) && (args.length != 3)) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manuadd | optional [world])"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manuadd | optional [world])"); return true; } - // Select the relevant world (if specified) if (args.length == 3) { dataHolder = worldsHolder.getWorldData(args[2]); permissionHandler = dataHolder.getPermissionsHandler(); } - // Validating state of sender if (dataHolder == null || permissionHandler == null) { if (!setDefaultWorldHandler(sender)) return true; } - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -347,14 +301,13 @@ public class GroupManager extends JavaPlugin { } auxGroup = dataHolder.getGroup(args[1]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return false; } if (auxGroup.isGlobal()) { sender.sendMessage(ChatColor.RED + "Players may not be members of GlobalGroups directly."); return false; } - // Validating permissions if (!isConsole && !isOpOverride && (senderGroup != null ? permissionHandler.inGroup(auxUser.getLastName(), senderGroup.getName()) : false)) { sender.sendMessage(ChatColor.RED + "Can't modify a player with the same permissions as you, or higher."); @@ -368,14 +321,11 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.RED + "You can't modify a player involving a group that you don't inherit."); return true; } - // Seems OK auxUser.setGroup(auxGroup); if (!sender.hasPermission("groupmanager.notify.other") || (isConsole)) sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getLastName() + "' group to '" + auxGroup.getName() + "' in world '" + dataHolder.getName() + "'."); - return true; - case manudel: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -384,13 +334,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manudel )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manudel )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -404,14 +353,11 @@ public class GroupManager extends JavaPlugin { // Seems OK dataHolder.removeUser(auxUser.getLastName()); sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getLastName() + "' to default settings."); - // If the player is online, this will create new data for the user. targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); if (targetPlayer != null) BukkitPermissions.updatePermissions(targetPlayer); - return true; - case manuaddsub: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -423,13 +369,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manuaddsub )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manuaddsub )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -437,7 +382,7 @@ public class GroupManager extends JavaPlugin { } auxGroup = dataHolder.getGroup(args[1]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } // Validating permission @@ -458,9 +403,7 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "You added subgroup '" + auxGroup.getName() + "' to player '" + auxUser.getLastName() + "'."); else sender.sendMessage(ChatColor.RED + "The subgroup '" + auxGroup.getName() + "' is already available to '" + auxUser.getLastName() + "'."); - return true; - case manudelsub: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -469,13 +412,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manudelsub )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manudelsub )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -483,10 +425,9 @@ public class GroupManager extends JavaPlugin { } auxGroup = dataHolder.getGroup(args[1]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } - // Validating permission if (!isConsole && !isOpOverride && (senderGroup != null ? permissionHandler.inGroup(auxUser.getLastName(), senderGroup.getName()) : false)) { sender.sendMessage(ChatColor.RED + "You can't modify a player with same permissions as you, or higher."); @@ -495,13 +436,10 @@ public class GroupManager extends JavaPlugin { // Seems OK auxUser.removeSubGroup(auxGroup); sender.sendMessage(ChatColor.YELLOW + "You removed subgroup '" + auxGroup.getName() + "' from player '" + auxUser.getLastName() + "' list."); - // targetPlayer = this.getServer().getPlayer(auxUser.getName()); // if (targetPlayer != null) // BukkitPermissions.updatePermissions(targetPlayer); - return true; - case mangadd: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -510,7 +448,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangadd )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangadd )"); return true; } auxGroup = dataHolder.getGroup(args[0]); @@ -521,9 +459,7 @@ public class GroupManager extends JavaPlugin { // Seems OK auxGroup = dataHolder.createGroup(args[0]); sender.sendMessage(ChatColor.YELLOW + "You created a group named: " + auxGroup.getName()); - return true; - case mangdel: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -532,22 +468,19 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangdel )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangdel )"); return false; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } // Seems OK dataHolder.removeGroup(auxGroup.getName()); sender.sendMessage(ChatColor.YELLOW + "You deleted a group named " + auxGroup.getName() + ", it's users are default group now."); - BukkitPermissions.updateAllPlayers(); - return true; - case manuaddp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -556,29 +489,24 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manuaddp [permission2] [permission3]...)"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manuaddp [permission2] [permission3]...)"); return true; } - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { auxUser = dataHolder.getUser(args[0]); } - // Validating your permissions if (!isConsole && !isOpOverride && (senderGroup != null ? permissionHandler.inGroup(auxUser.getLastName(), senderGroup.getName()) : false)) { sender.sendMessage(ChatColor.RED + "Can't modify player with same group than you, or higher."); return true; } - for (int i = 1; i < args.length; i++) { auxString = args[i].replace("'", ""); - permissionResult = permissionHandler.checkFullUserPermission(senderUser, auxString); if (!isConsole && !isOpOverride && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { sender.sendMessage(ChatColor.RED + "You can't add a permission you don't have: '" + auxString + "'"); @@ -593,13 +521,10 @@ public class GroupManager extends JavaPlugin { auxUser.addPermission(auxString); sender.sendMessage(ChatColor.YELLOW + "You added '" + auxString + "' to player '" + auxUser.getLastName() + "' permissions."); } - targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); if (targetPlayer != null) BukkitPermissions.updatePermissions(targetPlayer); - return true; - case manudelp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -608,23 +533,19 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manudelp [permission2] [permission3]...)"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manudelp [permission2] [permission3]...)"); return true; } - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { auxUser = dataHolder.getUser(args[0]); } - for (int i = 1; i < args.length; i++) { auxString = args[i].replace("'", ""); - if (!isConsole && !isOpOverride && (senderGroup != null ? permissionHandler.inGroup(auxUser.getLastName(), senderGroup.getName()) : false)) { sender.sendMessage(ChatColor.RED + "You can't modify a player with same group as you, or higher."); continue; @@ -650,13 +571,10 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "You removed '" + auxString + "' from player '" + auxUser.getLastName() + "' permissions."); } // Seems OK - targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); if (targetPlayer != null) BukkitPermissions.updatePermissions(targetPlayer); - return true; - case manuclearp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -665,14 +583,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manuclearp )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manuclearp )"); return true; } - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -692,13 +608,10 @@ public class GroupManager extends JavaPlugin { } } sender.sendMessage(ChatColor.YELLOW + "You removed all permissions from player '" + auxUser.getLastName() + "'."); - targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); if (targetPlayer != null) BukkitPermissions.updatePermissions(targetPlayer); - return true; - case manulistp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -707,14 +620,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if ((args.length == 0) || (args.length > 2)) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manulistp (+))"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manulistp (+))"); return true; } - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -750,7 +661,6 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "And all permissions from subgroups: " + auxString); } } - // bukkit perms if ((args.length == 2) && (args[1].equalsIgnoreCase("+"))) { targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); @@ -758,12 +668,9 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "Superperms reports: "); for (final String line : BukkitPermissions.listPerms(targetPlayer)) sender.sendMessage(ChatColor.YELLOW + line); - } } - return true; - case manucheckp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -772,16 +679,13 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manucheckp )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manucheckp )"); return true; } - auxString = args[1].replace("'", ""); - if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -790,11 +694,9 @@ public class GroupManager extends JavaPlugin { targetPlayer = this.getServer().getPlayer(auxUser.getLastName()); // Validating permission permissionResult = permissionHandler.checkFullGMPermission(auxUser, auxString, false); - if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { // No permissions found in GM so fall through and check Bukkit. sender.sendMessage(ChatColor.YELLOW + "The player doesn't have access to that permission"); - } else { // This permission was found in groupmanager. if (permissionResult.owner instanceof User) { @@ -817,14 +719,11 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); } } - // superperms if (targetPlayer != null) { sender.sendMessage(ChatColor.YELLOW + "SuperPerms reports Node: " + targetPlayer.hasPermission(args[1]) + ((!targetPlayer.hasPermission(args[1]) && targetPlayer.isPermissionSet(args[1])) ? " (Negated)" : "")); } - return true; - case mangaddp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -833,19 +732,16 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangaddp [permission2] [permission3]...)"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangaddp [permission2] [permission3]...)"); return true; } - auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return false; } - for (int i = 1; i < args.length; i++) { auxString = args[i].replace("'", ""); - // Validating your permissions permissionResult = permissionHandler.checkFullUserPermission(senderUser, auxString); if (!isConsole && !isOpOverride && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { @@ -861,11 +757,8 @@ public class GroupManager extends JavaPlugin { auxGroup.addPermission(auxString); sender.sendMessage(ChatColor.YELLOW + "You added '" + auxString + "' to group '" + auxGroup.getName() + "' permissions."); } - BukkitPermissions.updateAllPlayers(); - return true; - case mangdelp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -874,18 +767,16 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangdelp [permission2] [permission3]...)"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangdelp [permission2] [permission3]...)"); return true; } - auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } for (int i = 1; i < args.length; i++) { auxString = args[i].replace("'", ""); - // Validating your permissions permissionResult = permissionHandler.checkFullUserPermission(senderUser, auxString); if (!isConsole && !isOpOverride && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { @@ -907,11 +798,8 @@ public class GroupManager extends JavaPlugin { auxGroup.removePermission(auxString); sender.sendMessage(ChatColor.YELLOW + "You removed '" + auxString + "' from group '" + auxGroup.getName() + "' permissions."); } - BukkitPermissions.updateAllPlayers(); - return true; - case mangclearp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -920,16 +808,14 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangclearp )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangclearp )"); return true; } - auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } - for (final String perm : auxGroup.getPermissionList()) { permissionResult = permissionHandler.checkFullUserPermission(senderUser, perm); if (!isConsole && !isOpOverride && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { @@ -939,11 +825,8 @@ public class GroupManager extends JavaPlugin { } } sender.sendMessage(ChatColor.YELLOW + "You removed all permissions from group '" + auxGroup.getName() + "'."); - BukkitPermissions.updateAllPlayers(); - return true; - case manglistp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -952,16 +835,15 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manglistp )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manglistp )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } // Validating permission - // Seems OK auxString = ""; for (final String perm : auxGroup.getPermissionList()) { @@ -978,7 +860,6 @@ public class GroupManager extends JavaPlugin { auxString = auxString.substring(0, auxString.lastIndexOf(",")); sender.sendMessage(ChatColor.YELLOW + "And all permissions from groups: " + auxString); } - } else { sender.sendMessage(ChatColor.YELLOW + "The group '" + auxGroup.getName() + "' has no specific permissions."); auxString = ""; @@ -989,10 +870,8 @@ public class GroupManager extends JavaPlugin { auxString = auxString.substring(0, auxString.lastIndexOf(",")); sender.sendMessage(ChatColor.YELLOW + "Only all permissions from groups: " + auxString); } - } return true; - case mangcheckp: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1001,18 +880,16 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangcheckp )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangcheckp )"); return true; } - auxString = args[1]; if (auxString.startsWith("'") && auxString.endsWith("'")) { auxString = auxString.substring(1, auxString.length() - 1); } - auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } // Validating permission @@ -1032,10 +909,8 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "The group inherits the permission from group: " + permissionResult.owner.getLastName()); } sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); - } return true; - case mangaddi: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1044,24 +919,23 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangaddi )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangaddi )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } auxGroup2 = dataHolder.getGroup(args[1]); if (auxGroup2 == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { sender.sendMessage(ChatColor.RED + "GlobalGroups do NOT support inheritance."); return true; } - // Validating permission if (permissionHandler.hasGroupInInheritance(auxGroup, auxGroup2.getName())) { sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " already inherits " + auxGroup2.getName() + " (might not be directly)"); @@ -1070,11 +944,8 @@ public class GroupManager extends JavaPlugin { // Seems OK auxGroup.addInherits(auxGroup2); sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " is now in " + auxGroup.getName() + " inheritance list."); - BukkitPermissions.updateAllPlayers(); - return true; - case mangdeli: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1083,24 +954,23 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangdeli )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangdeli )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } auxGroup2 = dataHolder.getGroup(args[1]); if (auxGroup2 == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { sender.sendMessage(ChatColor.RED + "GlobalGroups do NOT support inheritance."); return true; } - // Validating permission if (!permissionHandler.hasGroupInInheritance(auxGroup, auxGroup2.getName())) { sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " does not inherits " + auxGroup2.getName() + "."); @@ -1113,11 +983,8 @@ public class GroupManager extends JavaPlugin { // Seems OK auxGroup.removeInherits(auxGroup2.getName()); sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " was removed from " + auxGroup.getName() + " inheritance list."); - BukkitPermissions.updateAllPlayers(); - return true; - case manuaddv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1126,13 +993,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 3) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manuaddv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manuaddv )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -1150,9 +1016,7 @@ public class GroupManager extends JavaPlugin { auxString = auxString.replace("'", ""); auxUser.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the user " + auxUser.getLastName()); - return true; - case manudelv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1161,13 +1025,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manudelv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manudelv )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { return false; } - if (match != null) { auxUser = dataHolder.getUser(match.get(0)); } else { @@ -1181,9 +1044,7 @@ public class GroupManager extends JavaPlugin { // Seems OK auxUser.getVariables().removeVar(args[1]); sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the user " + ChatColor.GREEN + auxUser.getLastName()); - return true; - case manulistv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1192,7 +1053,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manulistv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manulistv )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1216,9 +1077,7 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "Variables of user " + auxUser.getLastName() + ": "); sender.sendMessage(auxString + "."); sender.sendMessage(ChatColor.YELLOW + "Plus all variables from group: " + auxUser.getGroupName()); - return true; - case manucheckv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1227,7 +1086,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manucheckv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manucheckv )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1241,7 +1100,6 @@ public class GroupManager extends JavaPlugin { // Validating permission auxGroup = auxUser.getGroup(); auxGroup2 = permissionHandler.nextGroupWithVariable(auxGroup, args[1]); - if (!auxUser.getVariables().hasVar(args[1])) { // Check sub groups if (!auxUser.isSubGroupsEmpty() && auxGroup2 == null) @@ -1266,9 +1124,7 @@ public class GroupManager extends JavaPlugin { if (!auxGroup.equals(auxGroup2)) { sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); } - return true; - case mangaddv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1277,12 +1133,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length < 3) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangaddv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangaddv )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { @@ -1298,13 +1154,10 @@ public class GroupManager extends JavaPlugin { auxString += " "; } } - auxString = auxString.replace("'", ""); auxGroup.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the group " + auxGroup.getName()); - return true; - case mangdelv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1313,12 +1166,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangdelv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangdelv )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { @@ -1333,9 +1186,7 @@ public class GroupManager extends JavaPlugin { // Seems OK auxGroup.getVariables().removeVar(args[1]); sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the group " + ChatColor.GREEN + auxGroup.getName()); - return true; - case manglistv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1344,12 +1195,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manglistv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manglistv )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { @@ -1376,9 +1227,7 @@ public class GroupManager extends JavaPlugin { auxString = auxString.substring(0, auxString.lastIndexOf(",")); sender.sendMessage(ChatColor.YELLOW + "Plus all variables from groups: " + auxString); } - return true; - case mangcheckv: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1387,12 +1236,12 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mangcheckv )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/mangcheckv )"); return true; } auxGroup = dataHolder.getGroup(args[0]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[0] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[0] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { @@ -1410,9 +1259,7 @@ public class GroupManager extends JavaPlugin { if (!auxGroup.equals(auxGroup2)) { sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); } - return true; - case manwhois: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1421,7 +1268,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manwhois )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manwhois )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1433,8 +1280,8 @@ public class GroupManager extends JavaPlugin { auxUser = dataHolder.getUser(args[0]); } // Seems OK - sender.sendMessage(ChatColor.YELLOW + "Name: " + ChatColor.GREEN + auxUser.getLastName()); - sender.sendMessage(ChatColor.YELLOW + "Group: " + ChatColor.GREEN + auxUser.getGroup().getName()); + sender.sendMessage(ChatColor.YELLOW + "名称: " + ChatColor.GREEN + auxUser.getLastName()); + sender.sendMessage(ChatColor.YELLOW + "权限组: " + ChatColor.GREEN + auxUser.getGroup().getName()); // Compile a list of subgroups auxString = ""; for (final String subGroup : auxUser.subGroupListStringCopy()) { @@ -1444,7 +1291,6 @@ public class GroupManager extends JavaPlugin { auxString = auxString.substring(0, auxString.lastIndexOf(",")); sender.sendMessage(ChatColor.YELLOW + "subgroups: " + auxString); } - sender.sendMessage(ChatColor.YELLOW + "Overloaded: " + ChatColor.GREEN + dataHolder.isOverloaded(auxUser.getLastName())); auxGroup = dataHolder.surpassOverload(auxUser.getLastName()).getGroup(); if (!auxGroup.equals(auxUser.getGroup())) { @@ -1452,7 +1298,6 @@ public class GroupManager extends JavaPlugin { } // victim.permissions.add(args[1]); return true; - case tempadd: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1461,7 +1306,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/tempadd )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/tempadd )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1484,9 +1329,7 @@ public class GroupManager extends JavaPlugin { dataHolder.overloadUser(auxUser.getLastName()); overloadedUsers.get(dataHolder.getName().toLowerCase()).add(dataHolder.getUser(auxUser.getLastName())); sender.sendMessage(ChatColor.YELLOW + "Player set to overload mode!"); - return true; - case tempdel: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1495,7 +1338,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/tempdel )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/tempdel )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1519,10 +1362,8 @@ public class GroupManager extends JavaPlugin { if (overloadedUsers.get(dataHolder.getName().toLowerCase()).contains(auxUser)) { overloadedUsers.get(dataHolder.getName().toLowerCase()).remove(auxUser); } - sender.sendMessage(ChatColor.YELLOW + "Player overload mode is now disabled."); - + sender.sendMessage(ChatColor.YELLOW + "玩家超载模式现在被禁用."); return true; - case templist: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1542,7 +1383,7 @@ public class GroupManager extends JavaPlugin { } } if (count == 0) { - sender.sendMessage(ChatColor.YELLOW + "There are no users in overload mode."); + sender.sendMessage(ChatColor.YELLOW + "在重载模式下没有用户."); return true; } auxString = auxString.substring(0, auxString.lastIndexOf(",")); @@ -1551,9 +1392,7 @@ public class GroupManager extends JavaPlugin { } overloadedUsers.get(dataHolder.getName().toLowerCase()).removeAll(removeList); sender.sendMessage(ChatColor.YELLOW + " " + count + " Users in overload mode: " + ChatColor.WHITE + auxString); - return true; - case tempdelall: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1578,37 +1417,28 @@ public class GroupManager extends JavaPlugin { } overloadedUsers.get(dataHolder.getName().toLowerCase()).clear(); sender.sendMessage(ChatColor.YELLOW + " " + count + "All users in overload mode are now normal again."); - return true; - case mansave: - boolean forced = false; - if ((args.length == 1) && (args[0].equalsIgnoreCase("force"))) forced = true; - try { worldsHolder.saveChanges(forced); - sender.sendMessage(ChatColor.YELLOW + "All changes were saved."); + sender.sendMessage(ChatColor.YELLOW + "所有改变已保存."); } catch (final IllegalStateException ex) { sender.sendMessage(ChatColor.RED + ex.getMessage()); } return true; - case manload: - /** * Attempt to reload a specific world */ if (args.length > 0) { - if (!lastError.isEmpty()) { sender.sendMessage(ChatColor.RED + "All commands are locked due to an error. " + ChatColor.BOLD + "" + ChatColor.UNDERLINE + "Check plugins/groupmanager/error.log or console" + ChatColor.RESET + "" + ChatColor.RED + " and then try a '/manload'."); return true; } - auxString = ""; for (int i = 0; i < args.length; i++) { auxString += args[i]; @@ -1616,41 +1446,29 @@ public class GroupManager extends JavaPlugin { auxString += " "; } } - isLoaded = false; // Disable Bukkit Perms update and event triggers - globalGroups.load(); worldsHolder.loadWorld(auxString); - sender.sendMessage("The request to reload world '" + auxString + "' was attempted."); - isLoaded = true; - BukkitPermissions.reset(); - } else { - /** * Reload all settings and data as no world was specified. */ - /* * Attempting a fresh load. */ onDisable(true); onEnable(true); - sender.sendMessage("All settings and worlds were reloaded!"); } - /** * Fire an event as none will have been triggered in the reload. */ if (GroupManager.isLoaded()) GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.RELOADED); - return true; - case listgroups: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1674,9 +1492,7 @@ public class GroupManager extends JavaPlugin { } sender.sendMessage(ChatColor.YELLOW + "Groups Available: " + ChatColor.WHITE + auxString); sender.sendMessage(ChatColor.YELLOW + "GlobalGroups Available: " + ChatColor.WHITE + auxString2); - return true; - case manpromote: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1685,7 +1501,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manpromote )"); + sender.sendMessage(ChatColor.RED + "参数错误! (/manpromote )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1698,7 +1514,7 @@ public class GroupManager extends JavaPlugin { } auxGroup = dataHolder.getGroup(args[1]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { @@ -1729,10 +1545,8 @@ public class GroupManager extends JavaPlugin { // Seems OK auxUser.setGroup(auxGroup); if (!sender.hasPermission("groupmanager.notify.other") || (isConsole)) - sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getLastName() + " group to " + auxGroup.getName() + "."); - + sender.sendMessage(ChatColor.YELLOW + "你改变了 " + auxUser.getLastName() + " 的用户组为 " + auxGroup.getName() + "."); return true; - case mandemote: // Validating state of sender if (dataHolder == null || permissionHandler == null) { @@ -1741,7 +1555,7 @@ public class GroupManager extends JavaPlugin { } // Validating arguments if (args.length != 2) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mandemote )"); + sender.sendMessage(ChatColor.RED + "请检查参数! (/mandemote )"); return true; } if ((validateOnlinePlayer) && ((match = validatePlayer(args[0], sender)) == null)) { @@ -1754,11 +1568,11 @@ public class GroupManager extends JavaPlugin { } auxGroup = dataHolder.getGroup(args[1]); if (auxGroup == null) { - sender.sendMessage(ChatColor.RED + "'" + args[1] + "' Group doesnt exist!"); + sender.sendMessage(ChatColor.RED + "权限组 '" + args[1] + "' 不存在!"); return true; } if (auxGroup.isGlobal()) { - sender.sendMessage(ChatColor.RED + "Players may not be members of GlobalGroups directly."); + sender.sendMessage(ChatColor.RED + "玩家不可以直接是 全局组 的成员."); return true; } // Validating permission @@ -1785,10 +1599,8 @@ public class GroupManager extends JavaPlugin { // Seems OK auxUser.setGroup(auxGroup); if (!sender.hasPermission("groupmanager.notify.other") || (isConsole)) - sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getLastName() + " group to " + auxGroup.getName() + "."); - + sender.sendMessage(ChatColor.YELLOW + "你改变了 " + auxUser.getLastName() + " 的用户组为 " + auxGroup.getName() + "."); return true; - case mantogglevalidate: validateOnlinePlayer = !validateOnlinePlayer; sender.sendMessage(ChatColor.YELLOW + "Validate if player is online, now set to: " + Boolean.toString(validateOnlinePlayer)); @@ -1800,10 +1612,10 @@ public class GroupManager extends JavaPlugin { case mantogglesave: if (scheduler == null) { enableScheduler(); - sender.sendMessage(ChatColor.YELLOW + "The auto-saving is enabled!"); + sender.sendMessage(ChatColor.YELLOW + "自动保存已开启!"); } else { disableScheduler(); - sender.sendMessage(ChatColor.YELLOW + "The auto-saving is disabled!"); + sender.sendMessage(ChatColor.YELLOW + "自动保存已关闭!"); } return true; case manworld: @@ -1812,20 +1624,18 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + "You have the world '" + dataHolder.getName() + "' in your selection."); } else { if (dataHolder == null) { - sender.sendMessage(ChatColor.YELLOW + "There is no world selected. And no world is available now."); + sender.sendMessage(ChatColor.YELLOW + "没有选择世界。现在没有世界可以使用."); } else { - sender.sendMessage(ChatColor.YELLOW + "You don't have a world in your selection.."); - sender.sendMessage(ChatColor.YELLOW + "Working with the direct world where your player is."); - sender.sendMessage(ChatColor.YELLOW + "Your world now uses permissions of world name: '" + dataHolder.getName() + "' "); + sender.sendMessage(ChatColor.YELLOW + "在你的选择中没有一个世界.."); + sender.sendMessage(ChatColor.YELLOW + "系统将默认使用您所在的世界."); + sender.sendMessage(ChatColor.YELLOW + "您当前所在的世界为: '" + dataHolder.getName() + "' "); } } - return true; - case manselect: if (args.length < 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/manselect )"); - sender.sendMessage(ChatColor.YELLOW + "Worlds available: "); + sender.sendMessage(ChatColor.RED + "请检查参数! (/manselect )"); + sender.sendMessage(ChatColor.YELLOW + "可用的世界: "); final ArrayList worlds = worldsHolder.allWorldsDataList(); auxString = ""; for (int i = 0; i < worlds.size(); i++) { @@ -1840,7 +1650,7 @@ public class GroupManager extends JavaPlugin { auxString = ""; for (int i = 0; i < args.length; i++) { if (args[i] == null) { - logger.warning("Bukkit gave invalid arguments array! Cmd: " + cmd.getName() + " args.length: " + args.length); + logger.warning("Bukkit发送了无效的参数数组! Cmd: " + cmd.getName() + " args.length: " + args.length); return false; } auxString += args[i]; @@ -1851,24 +1661,20 @@ public class GroupManager extends JavaPlugin { dataHolder = worldsHolder.getWorldData(auxString); permissionHandler = dataHolder.getPermissionsHandler(); selectedWorlds.put(sender.getName(), dataHolder.getName()); - sender.sendMessage(ChatColor.YELLOW + "You have selected world '" + dataHolder.getName() + "'."); - + sender.sendMessage(ChatColor.YELLOW + "你选择了世界 '" + dataHolder.getName() + "'."); return true; - case manclear: if (args.length != 0) { - sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + sender.sendMessage(ChatColor.RED + "请检查参数!"); return false; } selectedWorlds.remove(sender.getName()); - sender.sendMessage(ChatColor.YELLOW + "You have removed your world selection. Working with current world(if possible)."); - + sender.sendMessage(ChatColor.YELLOW + "你已经取消了世界选择。默认将使用当前世界(如果可能的话)."); return true; - case mancheckw: if (args.length < 1) { - sender.sendMessage(ChatColor.RED + "Review your arguments count! (/mancheckw )"); - sender.sendMessage(ChatColor.YELLOW + "Worlds available: "); + sender.sendMessage(ChatColor.RED + "请检查参数! (/mancheckw )"); + sender.sendMessage(ChatColor.YELLOW + "可用的世界: "); final ArrayList worlds = worldsHolder.allWorldsDataList(); auxString = ""; for (int i = 0; i < worlds.size(); i++) { @@ -1880,11 +1686,10 @@ public class GroupManager extends JavaPlugin { sender.sendMessage(ChatColor.YELLOW + auxString); return false; } - auxString = ""; for (int i = 0; i < args.length; i++) { if (args[i] == null) { - logger.warning("Bukkit gave invalid arguments array! Cmd: " + cmd.getName() + " args.length: " + args.length); + logger.warning("Bukkit发送了无效的参数数组! Cmd: " + cmd.getName() + " args.length: " + args.length); return false; } auxString += args[i]; @@ -1893,37 +1698,30 @@ public class GroupManager extends JavaPlugin { } } dataHolder = worldsHolder.getWorldData(auxString); - - sender.sendMessage(ChatColor.YELLOW + "You have selected world '" + dataHolder.getName() + "'."); - sender.sendMessage(ChatColor.YELLOW + "This world is using the following data files.."); - sender.sendMessage(ChatColor.YELLOW + "Groups:" + ChatColor.GREEN + " " + dataHolder.getGroupsFile().getAbsolutePath()); - sender.sendMessage(ChatColor.YELLOW + "Users:" + ChatColor.GREEN + " " + dataHolder.getUsersFile().getAbsolutePath()); - + sender.sendMessage(ChatColor.YELLOW + "你选择了世界 '" + dataHolder.getName() + "'."); + sender.sendMessage(ChatColor.YELLOW + "这个世界正在使用下面的数据文件.."); + sender.sendMessage(ChatColor.YELLOW + "组:" + ChatColor.GREEN + " " + dataHolder.getGroupsFile().getAbsolutePath()); + sender.sendMessage(ChatColor.YELLOW + "用户:" + ChatColor.GREEN + " " + dataHolder.getUsersFile().getAbsolutePath()); return true; - default: break; } } - sender.sendMessage(ChatColor.RED + "You are not allowed to use that command."); + sender.sendMessage(ChatColor.RED + "你没有该命令的权限."); return true; } @Override public void onDisable() { - onDisable(false); } public void onDisable(final boolean restarting) { - setLoaded(false); - if (!restarting) { // Unregister this service if we are shutting down. this.getServer().getServicesManager().unregister(this.worldsHolder); } - disableScheduler(); // Shutdown before we save, so it doesn't interfere. if (worldsHolder != null) { try { @@ -1932,25 +1730,18 @@ public class GroupManager extends JavaPlugin { GroupManager.logger.log(Level.WARNING, ex.getMessage()); } } - // Remove all attachments before clearing if (BukkitPermissions != null) { BukkitPermissions.removeAllAttachments(); } - if (!restarting) { - if (WorldEvents != null) WorldEvents = null; - BukkitPermissions = null; - } - // EXAMPLE: Custom code, here we just output some info so we can check that all is well final PluginDescriptionFile pdfFile = this.getDescription(); - System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is disabled!"); - + System.out.println(pdfFile.getName() + " 版本 " + pdfFile.getVersion() + " 已卸载!"); if (!restarting) GroupManager.logger.removeHandler(ch); } @@ -1966,7 +1757,6 @@ public class GroupManager extends JavaPlugin { } public void onEnable(final boolean restarting) { - try { /* * reset local variables. @@ -1974,7 +1764,6 @@ public class GroupManager extends JavaPlugin { overloadedUsers = new HashMap>(); selectedWorlds = new HashMap(); lastError = ""; - /* * Setup our logger if we are not restarting. */ @@ -1984,14 +1773,12 @@ public class GroupManager extends JavaPlugin { GroupManager.logger.addHandler(ch); } GroupManager.logger.setLevel(Level.ALL); - // Create the backup folder, if it doesn't exist. prepareFileFields(); // Load the config.yml prepareConfig(); // Load the global groups globalGroups = new GlobalGroups(this); - /* * Configure the worlds holder. */ @@ -1999,23 +1786,20 @@ public class GroupManager extends JavaPlugin { worldsHolder = new WorldsHolder(this); else worldsHolder.resetWorldsHolder(); - /* * This should NEVER happen. No idea why it's still here. */ final PluginDescriptionFile pdfFile = this.getDescription(); if (worldsHolder == null) { - GroupManager.logger.severe("Can't enable " + pdfFile.getName() + " version " + pdfFile.getVersion() + ", bad loading!"); + GroupManager.logger.severe("无法启用 " + pdfFile.getName() + " 版本 " + pdfFile.getVersion() + ", 错误的载入!"); this.getServer().getPluginManager().disablePlugin(this); - throw new IllegalStateException("An error ocurred while loading GroupManager"); + throw new IllegalStateException("载入 GroupManager 时发生了一个错误!"); } - /* * Prevent our registered events from triggering * updates as we are not fully loaded. */ setLoaded(false); - /* * Initialize the world listener and bukkit permissions * to handle events if this is a fresh start @@ -2030,43 +1814,34 @@ public class GroupManager extends JavaPlugin { } else { BukkitPermissions.reset(); } - /* * Start the scheduler for data saving. */ enableScheduler(); - /* * Schedule a Bukkit Permissions update for 1 tick later. * All plugins will be loaded by then */ - if (getServer().getScheduler().scheduleSyncDelayedTask(this, new BukkitPermsUpdateTask(), 1) == -1) { - GroupManager.logger.severe("Could not schedule superperms Update."); + GroupManager.logger.severe("无法计划 Bukkit Permissions 刷新任务."); /* * Flag that we are now loaded and should start processing events. */ setLoaded(true); } - - System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); - + System.out.println(pdfFile.getName() + " 版本 " + pdfFile.getVersion() + " 已加载 汉化 By 喵♂呜!"); // Register as a service if (!restarting) this.getServer().getServicesManager().register(WorldsHolder.class, this.worldsHolder, this, ServicePriority.Lowest); - } catch (final Exception ex) { - /* * Store the error and write to the log. */ saveErrorLog(ex); - /* * Throw an error so Bukkit knows about it. */ throw new IllegalArgumentException(ex.getMessage(), ex); - } } @@ -2075,7 +1850,6 @@ public class GroupManager extends JavaPlugin { * the validateOnlinePlayer to set */ public void setValidateOnlinePlayer(final boolean validateOnlinePlayer) { - this.validateOnlinePlayer = validateOnlinePlayer; } @@ -2083,34 +1857,32 @@ public class GroupManager extends JavaPlugin { * Checks if a permission exists and of a lower or same priority. */ private boolean checkPermissionExists(final CommandSender sender, final String newPerm, final PermissionCheckResult oldPerm, final String type) { - if (newPerm.startsWith("+")) { if (oldPerm.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has direct access to that permission."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); + sender.sendMessage(ChatColor.RED + "当前 " + type + " 已经有直接访问权限."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); return true; } } else if (newPerm.startsWith("-")) { if (oldPerm.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has an exception for this node."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); + sender.sendMessage(ChatColor.RED + "当前 " + type + " 已经有例外(拒绝)权限."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); return true; } else if (oldPerm.resultType.equals(PermissionCheckResult.Type.NEGATION)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has a matching negated node."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); + sender.sendMessage(ChatColor.RED + "The " + type + " 已经有一个匹配节点."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); return true; } } else { if (oldPerm.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has an exception for this node."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); + sender.sendMessage(ChatColor.RED + "当前 " + type + " 已经有例外(拒绝)权限."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); } else if (oldPerm.resultType.equals(PermissionCheckResult.Type.NEGATION)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has a matching negated node."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); + sender.sendMessage(ChatColor.RED + "当前 " + type + " 已经有一个匹配节点."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); } else if (oldPerm.resultType.equals(PermissionCheckResult.Type.FOUND)) { - sender.sendMessage(ChatColor.RED + "The " + type + " already has direct access to that permission."); - sender.sendMessage(ChatColor.RED + "Node: " + oldPerm.accessLevel); - + sender.sendMessage(ChatColor.RED + "当前 " + type + " 已经有直接访问权限."); + sender.sendMessage(ChatColor.RED + "节点: " + oldPerm.accessLevel); // Since not all plugins define wildcard permissions, allow setting the permission anyway if the permissions dont match exactly. return (oldPerm.accessLevel.equalsIgnoreCase(newPerm)); } @@ -2119,12 +1891,10 @@ public class GroupManager extends JavaPlugin { } private void prepareConfig() { - config = new GMConfiguration(this); } private void prepareFileFields() { - backupFolder = new File(this.getDataFolder(), "backup"); if (!backupFolder.exists()) { getBackupFolder().mkdirs(); @@ -2137,58 +1907,46 @@ public class GroupManager extends JavaPlugin { * @param ex */ private void saveErrorLog(final Exception ex) { - if (!getDataFolder().exists()) { getDataFolder().mkdirs(); } - lastError = ex.getMessage(); - GroupManager.logger.severe("==================================================="); - GroupManager.logger.severe("= ERROR REPORT START - " + this.getDescription().getVersion() + " ="); + GroupManager.logger.severe("= 错误报告 开始 - " + this.getDescription().getVersion() + " ="); GroupManager.logger.severe("==================================================="); - GroupManager.logger.severe("=== PLEASE COPY AND PASTE THE ERROR.LOG FROM THE =="); - GroupManager.logger.severe("= GROUPMANAGER FOLDER TO AN ESSENTIALS DEVELOPER ="); + GroupManager.logger.severe("=== 请从插件目录复制错误日志ERROR.LOG发送给开发者 =="); GroupManager.logger.severe("==================================================="); GroupManager.logger.severe(lastError); GroupManager.logger.severe("==================================================="); - GroupManager.logger.severe("= ERROR REPORT ENDED ="); + GroupManager.logger.severe("= 错误报告 结束 ="); GroupManager.logger.severe("==================================================="); - // Append this error to the error log. try { - String error = "=============================== GM ERROR LOG ===============================\n"; + String error = "=============================== GM 错误日志 ===============================\n"; error += "= ERROR REPORT START - " + this.getDescription().getVersion() + " =\n\n"; - error += Tasks.getStackTraceAsString(ex); error += "\n============================================================================\n"; - Tasks.appendStringToFile(error, (getDataFolder() + System.getProperty("file.separator") + "ERROR.LOG")); } catch (final IOException e) { // Failed to write file. e.printStackTrace(); } - } /** * Sets up the default world for use. */ private boolean setDefaultWorldHandler(final CommandSender sender) { - dataHolder = worldsHolder.getWorldData(worldsHolder.getDefaultWorld().getName()); permissionHandler = dataHolder.getPermissionsHandler(); - if ((dataHolder != null) && (permissionHandler != null)) { selectedWorlds.put(sender.getName(), dataHolder.getName()); - sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. Default world '" + worldsHolder.getDefaultWorld().getName() + "' selected."); + sender.sendMessage(ChatColor.RED + "无法确定你所在的世界,已选择默认世界 '" + worldsHolder.getDefaultWorld().getName()); return true; } - - sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); - sender.sendMessage(ChatColor.RED + "Use /manselect "); + sender.sendMessage(ChatColor.RED + "无法确定你所在的世界,请指定一个世界."); + sender.sendMessage(ChatColor.RED + "使用 /manselect "); return false; - } /** @@ -2200,10 +1958,8 @@ public class GroupManager extends JavaPlugin { * @return true if a single match is found */ private List validatePlayer(final String playerName, final CommandSender sender) { - List players = new ArrayList(); final List match = new ArrayList(); - players = this.getServer().matchPlayer(playerName); if (players.isEmpty()) { // Check for an offline player (exact match). @@ -2216,22 +1972,18 @@ public class GroupManager extends JavaPlugin { match.add(offline.getName()); } } - } else { for (final Player player : players) { match.add(player.getName()); } } - if (match.isEmpty() || match == null) { - sender.sendMessage(ChatColor.RED + "Player not found!"); + sender.sendMessage(ChatColor.RED + "玩家未找到!"); return null; } else if (match.size() > 1) { - sender.sendMessage(ChatColor.RED + "Too many matches found! (" + match.toString() + ")"); + sender.sendMessage(ChatColor.RED + "过多的参数! (" + match.toString() + ")"); return null; } - return match; - } } diff --git a/src/main/java/org/anjocaido/groupmanager/Tasks/BukkitPermsUpdateTask.java b/src/main/java/org/anjocaido/groupmanager/Tasks/BukkitPermsUpdateTask.java index 6db4b20..2a9b48e 100644 --- a/src/main/java/org/anjocaido/groupmanager/Tasks/BukkitPermsUpdateTask.java +++ b/src/main/java/org/anjocaido/groupmanager/Tasks/BukkitPermsUpdateTask.java @@ -3,27 +3,23 @@ package org.anjocaido.groupmanager.Tasks; import org.anjocaido.groupmanager.GroupManager; /* - * + * * Created by ElgarL */ public class BukkitPermsUpdateTask implements Runnable { public BukkitPermsUpdateTask() { - super(); } @Override public void run() { - // Signal loaded and update BukkitPermissions. GroupManager.setLoaded(true); GroupManager.BukkitPermissions.collectPermissions(); GroupManager.BukkitPermissions.updateAllPlayers(); - - GroupManager.logger.info("Bukkit Permissions Updated!"); - + GroupManager.logger.info("权限已更新!"); } } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/data/DataUnit.java b/src/main/java/org/anjocaido/groupmanager/data/DataUnit.java index 2dc9150..ee3716d 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/DataUnit.java +++ b/src/main/java/org/anjocaido/groupmanager/data/DataUnit.java @@ -13,39 +13,44 @@ import org.anjocaido.groupmanager.dataholder.WorldDataHolder; import org.anjocaido.groupmanager.utils.StringPermissionComparator; /** - * + * * @author gabrielcouto */ public abstract class DataUnit { - private WorldDataHolder dataSource; - private String uUID; + private final String uUID; private String lastName; private boolean changed, sorted = false; private List permissions = Collections.unmodifiableList(Collections. emptyList()); - public DataUnit(WorldDataHolder dataSource, String name) { + public DataUnit(final String name) { + this.uUID = name; + } + public DataUnit(final WorldDataHolder dataSource, final String name) { this.dataSource = dataSource; this.uUID = name; } - public DataUnit(String name) { - - this.uUID = name; + public void addPermission(final String permission) { + if (!hasSamePermissionNode(permission)) { + final List clone = new ArrayList(permissions); + clone.add(permission); + permissions = Collections.unmodifiableList(clone); + } + flagAsChanged(); } /** * Every group is matched only by their names and DataSources names. - * + * * @param o * @return true if they are equal. false if not. */ @Override - public boolean equals(Object o) { - + public boolean equals(final Object o) { if (o instanceof DataUnit) { - DataUnit go = (DataUnit) o; + final DataUnit go = (DataUnit) o; if (this.getUUID().equalsIgnoreCase(go.getUUID())) { // Global Group match. if (this.dataSource == null && go.getDataSource() == null) @@ -64,68 +69,13 @@ public abstract class DataUnit { return false; } - @Override - public int hashCode() { - - int hash = 5; - hash = 71 * hash + (this.uUID != null ? this.uUID.toLowerCase().hashCode() : 0); - return hash; - } - - /** - * Set the data source to point to a different worldDataHolder - * - * @param source - */ - public void setDataSource(WorldDataHolder source) { - - this.dataSource = source; - } - - /** - * Get the current worldDataHolder this object is pointing to - * - * @return the dataSource - */ - public WorldDataHolder getDataSource() { - - return dataSource; - } - - public String getUUID() { - - return uUID; - } - - public String getLastName() { - - if (uUID.length() < 36) - return this.uUID; - - return this.lastName; - } - - public void setLastName(String lastName) { - - if (!lastName.equals(this.lastName)) { - - this.lastName = lastName; - changed = true; - - } - - } - public void flagAsChanged() { - - WorldDataHolder testSource = getDataSource(); + final WorldDataHolder testSource = getDataSource(); String source = ""; - if (testSource == null) source = "GlobalGroups"; else source = testSource.getName(); - GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as changed!"); // for(StackTraceElement st: Thread.currentThread().getStackTrace()){ // GroupManager.logger.finest(st.toString()); @@ -134,53 +84,36 @@ public abstract class DataUnit { changed = true; } - public boolean isChanged() { - - return changed; - } - public void flagAsSaved() { - - WorldDataHolder testSource = getDataSource(); + final WorldDataHolder testSource = getDataSource(); String source = ""; - if (testSource == null) source = "GlobalGroups"; else source = testSource.getName(); - GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as saved!"); changed = false; } - public boolean hasSamePermissionNode(String permission) { - - return permissions.contains(permission); + /** + * Get the current worldDataHolder this object is pointing to + * + * @return the dataSource + */ + public WorldDataHolder getDataSource() { + return dataSource; } - public void addPermission(String permission) { - - if (!hasSamePermissionNode(permission)) { - List clone = new ArrayList(permissions); - clone.add(permission); - permissions = Collections.unmodifiableList(clone); - } - flagAsChanged(); - } - - public boolean removePermission(String permission) { - - flagAsChanged(); - List clone = new ArrayList(permissions); - boolean ret = clone.remove(permission); - permissions = Collections.unmodifiableList(clone); - return ret; + public String getLastName() { + if (uUID.length() < 36) + return this.uUID; + return this.lastName; } /** * Use this only to list permissions. * You can't edit the permissions using the returned ArrayList instance - * + * * @return a copy of the permission list */ public List getPermissionList() { @@ -188,15 +121,56 @@ public abstract class DataUnit { return permissions; } - public boolean isSorted() { + public String getUUID() { + return uUID; + } + @Override + public int hashCode() { + int hash = 5; + hash = 71 * hash + (this.uUID != null ? this.uUID.toLowerCase().hashCode() : 0); + return hash; + } + + public boolean hasSamePermissionNode(final String permission) { + return permissions.contains(permission); + } + + public boolean isChanged() { + return changed; + } + + public boolean isSorted() { return this.sorted; } - public void sortPermissions() { + public boolean removePermission(final String permission) { + flagAsChanged(); + final List clone = new ArrayList(permissions); + final boolean ret = clone.remove(permission); + permissions = Collections.unmodifiableList(clone); + return ret; + } + /** + * Set the data source to point to a different worldDataHolder + * + * @param source + */ + public void setDataSource(final WorldDataHolder source) { + this.dataSource = source; + } + + public void setLastName(final String lastName) { + if (!lastName.equals(this.lastName)) { + this.lastName = lastName; + changed = true; + } + } + + public void sortPermissions() { if (!isSorted()) { - List clone = new ArrayList(permissions); + final List clone = new ArrayList(permissions); Collections.sort(clone, StringPermissionComparator.getInstance()); permissions = Collections.unmodifiableList(clone); sorted = true; diff --git a/src/main/java/org/anjocaido/groupmanager/data/Group.java b/src/main/java/org/anjocaido/groupmanager/data/Group.java index 6df5357..0975db5 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/Group.java +++ b/src/main/java/org/anjocaido/groupmanager/data/Group.java @@ -18,7 +18,6 @@ import org.anjocaido.groupmanager.events.GMGroupEvent.Action; * @author gabrielcouto/ElgarL */ public class Group extends DataUnit implements Cloneable { - /** * The group it inherits DIRECTLY! */ @@ -36,7 +35,6 @@ public class Group extends DataUnit implements Cloneable { * @param name */ public Group(final String name) { - super(name); } @@ -46,7 +44,6 @@ public class Group extends DataUnit implements Cloneable { * @param name */ public Group(final WorldDataHolder source, final String name) { - super(source, name); } @@ -55,7 +52,6 @@ public class Group extends DataUnit implements Cloneable { * the inherits to set */ public void addInherits(final Group inherit) { - if (!isGlobal()) { if (!this.getDataSource().groupExists(inherit.getName())) { getDataSource().addGroup(inherit); @@ -80,16 +76,13 @@ public class Group extends DataUnit implements Cloneable { */ @Override public Group clone() { - Group clone; - if (isGlobal()) { clone = new Group(this.getName()); } else { clone = new Group(getDataSource(), this.getName()); clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections. emptyList()) : Collections.unmodifiableList(new ArrayList(this.getInherits())); } - for (final String perm : this.getPermissionList()) { clone.addPermission(perm); } @@ -105,13 +98,10 @@ public class Group extends DataUnit implements Cloneable { * @return Null or Clone */ public Group clone(final WorldDataHolder dataSource) { - if (dataSource.groupExists(this.getName())) { return null; } - final Group clone = dataSource.createGroup(this.getName()); - // Don't add inheritance for GlobalGroups if (!isGlobal()) { clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections. emptyList()) : Collections.unmodifiableList(new ArrayList(this.getInherits())); @@ -139,7 +129,6 @@ public class Group extends DataUnit implements Cloneable { * @return the name */ public String getName() { - return this.getUUID(); } @@ -147,7 +136,6 @@ public class Group extends DataUnit implements Cloneable { * @return the variables */ public GroupVariables getVariables() { - return variables; } @@ -157,12 +145,10 @@ public class Group extends DataUnit implements Cloneable { * @return true if this is a global group */ public boolean isGlobal() { - return (getDataSource() == null); } public boolean removeInherits(final String inherit) { - if (!isGlobal()) { if (this.inherits.contains(inherit.toLowerCase())) { final List clone = new ArrayList(inherits); @@ -181,7 +167,6 @@ public class Group extends DataUnit implements Cloneable { * @param varList */ public void setVariables(final Map varList) { - if (!isGlobal()) { final GroupVariables temp = new GroupVariables(this, varList); variables.clearVars(); diff --git a/src/main/java/org/anjocaido/groupmanager/data/GroupVariables.java b/src/main/java/org/anjocaido/groupmanager/data/GroupVariables.java index 21ecc7d..bc3cbd3 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/GroupVariables.java +++ b/src/main/java/org/anjocaido/groupmanager/data/GroupVariables.java @@ -11,7 +11,6 @@ import java.util.Map; * @author gabrielcouto */ public class GroupVariables extends Variables implements Cloneable { - private final Group owner; public GroupVariables(final Group owner) { @@ -23,7 +22,6 @@ public class GroupVariables extends Variables implements Cloneable { } public GroupVariables(final Group owner, final Map varList) { - super(owner); variables.clear(); variables.putAll(varList); @@ -32,13 +30,11 @@ public class GroupVariables extends Variables implements Cloneable { owner.flagAsChanged(); } // thisGrp.prefix = infoNode.get("prefix").toString(); - if (variables.get("suffix") == null) { variables.put("suffix", ""); owner.flagAsChanged(); } // thisGrp.suffix = infoNode.get("suffix").toString(); - if (variables.get("build") == null) { variables.put("build", false); owner.flagAsChanged(); @@ -51,7 +47,6 @@ public class GroupVariables extends Variables implements Cloneable { */ @Override public Group getOwner() { - return owner; } @@ -62,7 +57,6 @@ public class GroupVariables extends Variables implements Cloneable { */ @Override public void removeVar(final String name) { - try { this.variables.remove(name); } catch (final Exception e) { @@ -83,7 +77,6 @@ public class GroupVariables extends Variables implements Cloneable { * @return GroupVariables clone */ protected GroupVariables clone(final Group newOwner) { - final GroupVariables clone = new GroupVariables(newOwner); synchronized (variables) { for (final String key : variables.keySet()) { diff --git a/src/main/java/org/anjocaido/groupmanager/data/User.java b/src/main/java/org/anjocaido/groupmanager/data/User.java index 6e48086..f970c18 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/User.java +++ b/src/main/java/org/anjocaido/groupmanager/data/User.java @@ -21,7 +21,6 @@ import org.bukkit.entity.Player; * @author gabrielcouto/ElgarL */ public class User extends DataUnit implements Cloneable { - private String group = null; private final List subGroups = Collections.synchronizedList(new ArrayList()); /** @@ -36,13 +35,11 @@ public class User extends DataUnit implements Cloneable { * @param name */ public User(final WorldDataHolder source, final String name) { - super(source, name); this.group = source.getDefaultGroup().getName(); } public boolean addSubGroup(final Group subGroup) { - // Don't allow adding a subgroup if it's already set as the primary. if (this.group.equalsIgnoreCase(subGroup.getName())) { return false; @@ -50,12 +47,10 @@ public class User extends DataUnit implements Cloneable { // User already has this subgroup if (containsSubGroup(subGroup)) return false; - // If the group doesn't exists add it if (!this.getDataSource().groupExists(subGroup.getName())) { getDataSource().addGroup(subGroup); } - subGroups.add(subGroup.getName()); flagAsChanged(); if (GroupManager.isLoaded()) { @@ -64,7 +59,6 @@ public class User extends DataUnit implements Cloneable { GroupManager.getGMEventHandler().callEvent(this, Action.USER_SUBGROUP_CHANGED); } return true; - // subGroup = getDataSource().getGroup(subGroup.getName()); // removeSubGroup(subGroup); // subGroups.add(subGroup.getName()); @@ -76,13 +70,10 @@ public class User extends DataUnit implements Cloneable { */ @Override public User clone() { - final User clone = new User(getDataSource(), this.getLastName()); clone.group = this.group; - // Clone all subgroups. clone.subGroups.addAll(this.subGroupListStringCopy()); - for (final String perm : this.getPermissionList()) { clone.addPermission(perm); } @@ -92,24 +83,17 @@ public class User extends DataUnit implements Cloneable { } public User clone(final String uUID, final String CurrentName) { - final User clone = this.getDataSource().createUser(uUID); - clone.setLastName(CurrentName); - // Set the group silently. clone.setGroup(this.getDataSource().getGroup(this.getGroupName()), false); - // Clone all subgroups. clone.subGroups.addAll(this.subGroupListStringCopy()); - for (final String perm : this.getPermissionList()) { clone.addPermission(perm); } - clone.variables = this.variables.clone(this); clone.flagAsChanged(); - return clone; } @@ -120,38 +104,30 @@ public class User extends DataUnit implements Cloneable { * @return null if given dataSource already contains the same user */ public User clone(final WorldDataHolder dataSource) { - if (dataSource.isUserDeclared(this.getUUID())) { return null; } - final User clone = dataSource.createUser(this.getUUID()); - if (dataSource.getGroup(group) == null) { clone.setGroup(dataSource.getDefaultGroup()); } else { clone.setGroup(dataSource.getGroup(this.getGroupName())); } - // Clone all subgroups. clone.subGroups.addAll(this.subGroupListStringCopy()); - for (final String perm : this.getPermissionList()) { clone.addPermission(perm); } - clone.variables = this.variables.clone(this); clone.flagAsChanged(); return clone; } public boolean containsSubGroup(final Group subGroup) { - return subGroups.contains(subGroup.getName()); } public Player getBukkitPlayer() { - if (bukkitPlayer == null) { bukkitPlayer = Bukkit.getPlayer(this.getLastName()); } @@ -159,7 +135,6 @@ public class User extends DataUnit implements Cloneable { } public Group getGroup() { - Group result = getDataSource().getGroup(group); if (result == null) { this.setGroup(getDataSource().getDefaultGroup()); @@ -172,7 +147,6 @@ public class User extends DataUnit implements Cloneable { * @return the group */ public String getGroupName() { - final Group result = getDataSource().getGroup(group); if (result == null) { group = getDataSource().getDefaultGroup().getName(); @@ -188,26 +162,21 @@ public class User extends DataUnit implements Cloneable { */ @Deprecated public String getName() { - return this.getLastName(); - } /** * @return the variables */ public UserVariables getVariables() { - return variables; } public boolean isSubGroupsEmpty() { - return subGroups.isEmpty(); } public boolean removeSubGroup(final Group subGroup) { - try { if (subGroups.remove(subGroup.getName())) { flagAsChanged(); @@ -227,7 +196,6 @@ public class User extends DataUnit implements Cloneable { * the group to set */ public void setGroup(final Group group) { - setGroup(group, true); } @@ -239,7 +207,6 @@ public class User extends DataUnit implements Cloneable { * */ public void setGroup(Group group, final Boolean updatePerms) { - if (!this.getDataSource().groupExists(group.getName())) { getDataSource().addGroup(group); } @@ -250,17 +217,14 @@ public class User extends DataUnit implements Cloneable { if (GroupManager.isLoaded()) { if (!GroupManager.BukkitPermissions.isPlayer_join() && (updatePerms)) GroupManager.BukkitPermissions.updatePlayer(getBukkitPlayer()); - // Do we notify of the group change? final String defaultGroupName = getDataSource().getDefaultGroup().getName(); // if we were not in the default group // or we were in the default group and the move is to a different // group. final boolean notify = (!oldGroup.equalsIgnoreCase(defaultGroupName)) || ((oldGroup.equalsIgnoreCase(defaultGroupName)) && (!this.group.equalsIgnoreCase(defaultGroupName))); - if (notify) GroupManager.notify(this.getLastName(), String.format(" moved to the group %s in %s.", group.getName(), this.getDataSource().getName())); - if (updatePerms) GroupManager.getGMEventHandler().callEvent(this, Action.USER_GROUP_CHANGED); } @@ -271,7 +235,6 @@ public class User extends DataUnit implements Cloneable { * @param varList */ public void setVariables(final Map varList) { - // UserVariables temp = new UserVariables(this, varList); variables.clearVars(); for (final String key : varList.keySet()) { @@ -286,7 +249,6 @@ public class User extends DataUnit implements Cloneable { } public ArrayList subGroupListCopy() { - final ArrayList val = new ArrayList(); synchronized (subGroups) { for (final String gstr : subGroups) { @@ -308,12 +270,10 @@ public class User extends DataUnit implements Cloneable { } public int subGroupsSize() { - return subGroups.size(); } public User updatePlayer(final Player player) { - bukkitPlayer = player; return this; } diff --git a/src/main/java/org/anjocaido/groupmanager/data/UserVariables.java b/src/main/java/org/anjocaido/groupmanager/data/UserVariables.java index 43ce5b6..4bfc8ba 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/UserVariables.java +++ b/src/main/java/org/anjocaido/groupmanager/data/UserVariables.java @@ -11,11 +11,9 @@ import java.util.Map; * @author gabrielcouto */ public class UserVariables extends Variables { - private final User owner; public UserVariables(final User owner) { - super(owner); this.owner = owner; } @@ -32,7 +30,6 @@ public class UserVariables extends Variables { */ @Override public User getOwner() { - return owner; } @@ -42,7 +39,6 @@ public class UserVariables extends Variables { * @return UserVariables clone */ protected UserVariables clone(final User newOwner) { - final UserVariables clone = new UserVariables(newOwner); synchronized (variables) { for (final String key : variables.keySet()) { diff --git a/src/main/java/org/anjocaido/groupmanager/data/Variables.java b/src/main/java/org/anjocaido/groupmanager/data/Variables.java index 48953a3..f37d42b 100644 --- a/src/main/java/org/anjocaido/groupmanager/data/Variables.java +++ b/src/main/java/org/anjocaido/groupmanager/data/Variables.java @@ -15,32 +15,48 @@ import java.util.Map; * prefix * suffix * build - * + * * @author gabrielcouto */ public abstract class Variables implements Cloneable { - - private DataUnit owner; + private final DataUnit owner; protected final Map variables = Collections.synchronizedMap(new HashMap()); - public Variables(DataUnit owner) { - + public Variables(final DataUnit owner) { this.owner = owner; } + public static Object parseVariableValue(final String value) { + try { + final Integer i = Integer.parseInt(value); + return i; + } catch (final NumberFormatException e) { + } + try { + final Double d = Double.parseDouble(value); + return d; + } catch (final NumberFormatException e) { + } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { + return true; + } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { + return false; + } + return value; + } + /** * Add var to the the INFO node. * examples: * addVar("build",true); * addVar("prefix","c"); - * + * * @param name * key name of the var * @param o * the object value of the var */ - public void addVar(String name, Object o) { - + public void addVar(final String name, final Object o) { if (o == null) { return; } @@ -51,82 +67,72 @@ public abstract class Variables implements Cloneable { owner.flagAsChanged(); } - /** - * Returns the object inside the var - * - * @param name - * @return a Object if exists. null if doesn't exists - */ - public Object getVarObject(String name) { - - return variables.get(name); + public void clearVars() { + variables.clear(); + owner.flagAsChanged(); } /** - * Get the String value for the given var name - * - * @param name - * the var key name - * @return "" if null. or the toString() value of object + * @return the owner */ - public String getVarString(String name) { - - Object o = variables.get(name); - try { - return o == null ? "" : o.toString(); - } catch (Exception e) { - return ""; - } + public DataUnit getOwner() { + return owner; } /** - * + * Returns the quantity of vars this is holding + * + * @return the number of vars + */ + public int getSize() { + return variables.size(); + } + + /** + * * @param name * @return false if null. or a Boolean.parseBoolean of the string */ - public Boolean getVarBoolean(String name) { - - Object o = variables.get(name); + public Boolean getVarBoolean(final String name) { + final Object o = variables.get(name); try { return o == null ? false : Boolean.parseBoolean(o.toString()); - } catch (Exception e) { + } catch (final Exception e) { return false; } } /** - * - * @param name - * @return -1 if null. or a parseInt of the string - */ - public Integer getVarInteger(String name) { - - Object o = variables.get(name); - try { - return o == null ? -1 : Integer.parseInt(o.toString()); - } catch (Exception e) { - return -1; - } - } - - /** - * + * * @param name * @return -1 if null. or a parseDouble of the string */ - public Double getVarDouble(String name) { - - Object o = variables.get(name); + public Double getVarDouble(final String name) { + final Object o = variables.get(name); try { return o == null ? -1.0D : Double.parseDouble(o.toString()); - } catch (Exception e) { + } catch (final Exception e) { return -1.0D; } } + /** + * + * @param name + * @return -1 if null. or a parseInt of the string + */ + public Integer getVarInteger(final String name) { + final Object o = variables.get(name); + try { + return o == null ? -1 : Integer.parseInt(o.toString()); + } catch (final Exception e) { + return -1; + } + } + /** * All variable keys this is holding - * + * * @return Set of all variable names. */ public String[] getVarKeyList() { @@ -135,79 +141,57 @@ public abstract class Variables implements Cloneable { } } + /** + * Returns the object inside the var + * + * @param name + * @return a Object if exists. null if doesn't exists + */ + public Object getVarObject(final String name) { + return variables.get(name); + } + + /** + * Get the String value for the given var name + * + * @param name + * the var key name + * @return "" if null. or the toString() value of object + */ + public String getVarString(final String name) { + final Object o = variables.get(name); + try { + return o == null ? "" : o.toString(); + } catch (final Exception e) { + return ""; + } + } + /** * verify is a var exists - * + * * @param name * the key name of the var * @return true if that var exists */ - public boolean hasVar(String name) { - + public boolean hasVar(final String name) { return variables.containsKey(name); } - /** - * Returns the quantity of vars this is holding - * - * @return the number of vars - */ - public int getSize() { - - return variables.size(); + public boolean isEmpty() { + return variables.isEmpty(); } /** * Remove a var from the list - * + * * @param name */ - public void removeVar(String name) { - + public void removeVar(final String name) { try { variables.remove(name); - } catch (Exception e) { + } catch (final Exception e) { } owner.flagAsChanged(); } - - public static Object parseVariableValue(String value) { - - try { - Integer i = Integer.parseInt(value); - return i; - } catch (NumberFormatException e) { - } - try { - Double d = Double.parseDouble(value); - return d; - } catch (NumberFormatException e) { - } - if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { - return true; - } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { - return false; - } - return value; - - } - - public void clearVars() { - - variables.clear(); - owner.flagAsChanged(); - } - - /** - * @return the owner - */ - public DataUnit getOwner() { - - return owner; - } - - public boolean isEmpty() { - - return variables.isEmpty(); - } } diff --git a/src/main/java/org/anjocaido/groupmanager/dataholder/GroupsDataHolder.java b/src/main/java/org/anjocaido/groupmanager/dataholder/GroupsDataHolder.java index 9fc6b97..79cfe2a 100644 --- a/src/main/java/org/anjocaido/groupmanager/dataholder/GroupsDataHolder.java +++ b/src/main/java/org/anjocaido/groupmanager/dataholder/GroupsDataHolder.java @@ -9,18 +9,16 @@ import org.anjocaido.groupmanager.data.Group; /** * This container holds all Groups loaded from the relevant groupsFile. - * + * * @author ElgarL - * + * */ public class GroupsDataHolder { - private WorldDataHolder dataSource; private Group defaultGroup = null; private File groupsFile; private boolean haveGroupsChanged = false; private long timeStampGroups = 0; - /** * The actual groups holder */ @@ -30,21 +28,9 @@ public class GroupsDataHolder { * Constructor */ protected GroupsDataHolder() { - - } - - public void setDataSource(WorldDataHolder dataSource) { - - this.dataSource = dataSource; - // push this data source to the users, so they pull the correct groups data. - synchronized (groups) { - for (Group group : groups.values()) - group.setDataSource(this.dataSource); - } } public WorldDataHolder getDataSource() { - return this.dataSource; } @@ -52,29 +38,39 @@ public class GroupsDataHolder { * @return the defaultGroup */ public Group getDefaultGroup() { - return defaultGroup; } - /** - * @param defaultGroup - * the defaultGroup to set - */ - public void setDefaultGroup(Group defaultGroup) { - - this.defaultGroup = defaultGroup; - } - /** * Note: Iteration over this object has to be synchronized! - * + * * @return the groups */ public Map getGroups() { - return groups; } + /** + * @return the groupsFile + */ + public File getGroupsFile() { + return groupsFile; + } + + /** + * @return the timeStampGroups + */ + public long getTimeStampGroups() { + return timeStampGroups; + } + + /** + * @return the haveGroupsChanged + */ + public boolean HaveGroupsChanged() { + return haveGroupsChanged; + } + /** * Resets the Groups */ @@ -82,55 +78,44 @@ public class GroupsDataHolder { this.groups.clear(); } - /** - * @return the groupsFile - */ - public File getGroupsFile() { - - return groupsFile; + public void setDataSource(final WorldDataHolder dataSource) { + this.dataSource = dataSource; + // push this data source to the users, so they pull the correct groups data. + synchronized (groups) { + for (final Group group : groups.values()) + group.setDataSource(this.dataSource); + } } /** - * @param groupsFile - * the groupsFile to set + * @param defaultGroup + * the defaultGroup to set */ - public void setGroupsFile(File groupsFile) { - - this.groupsFile = groupsFile; - } - - /** - * @return the haveGroupsChanged - */ - public boolean HaveGroupsChanged() { - - return haveGroupsChanged; + public void setDefaultGroup(final Group defaultGroup) { + this.defaultGroup = defaultGroup; } /** * @param haveGroupsChanged * the haveGroupsChanged to set */ - public void setGroupsChanged(boolean haveGroupsChanged) { - + public void setGroupsChanged(final boolean haveGroupsChanged) { this.haveGroupsChanged = haveGroupsChanged; } /** - * @return the timeStampGroups + * @param groupsFile + * the groupsFile to set */ - public long getTimeStampGroups() { - - return timeStampGroups; + public void setGroupsFile(final File groupsFile) { + this.groupsFile = groupsFile; } /** * @param timeStampGroups * the timeStampGroups to set */ - public void setTimeStampGroups(long timeStampGroups) { - + public void setTimeStampGroups(final long timeStampGroups) { this.timeStampGroups = timeStampGroups; } - } diff --git a/src/main/java/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java b/src/main/java/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java index 59c8496..884b526 100644 --- a/src/main/java/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java +++ b/src/main/java/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java @@ -9,25 +9,24 @@ import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import org.anjocaido.groupmanager.data.User; /** - * + * * @author gabrielcouto */ public class OverloadedWorldHolder extends WorldDataHolder { - /** * */ protected final Map overloadedUsers = Collections.synchronizedMap(new HashMap()); /** - * + * * @param ph */ - public OverloadedWorldHolder(WorldDataHolder ph) { - + public OverloadedWorldHolder(final WorldDataHolder ph) { super(ph.getName()); this.setGroupsFile(ph.getGroupsFile()); this.setUsersFile(ph.getUsersFile()); @@ -36,30 +35,11 @@ public class OverloadedWorldHolder extends WorldDataHolder { } /** - * - * @param userName - * @return user object or a new user if none exists. - */ - @Override - public User getUser(String userName) { - - // OVERLOADED CODE - String userNameLowered = userName.toLowerCase(); - if (overloadedUsers.containsKey(userNameLowered)) { - return overloadedUsers.get(userNameLowered); - } - // END CODE - - return super.getUser(userName); - } - - /** - * + * * @param theUser */ @Override public void addUser(User theUser) { - if (theUser.getDataSource() != this) { theUser = theUser.clone(this); } @@ -82,13 +62,116 @@ public class OverloadedWorldHolder extends WorldDataHolder { } /** - * + * + * @param userName + * @return user object or a new user if none exists. + */ + @Override + public User getUser(final String userName) { + // OVERLOADED CODE + final String userNameLowered = userName.toLowerCase(); + if (overloadedUsers.containsKey(userNameLowered)) { + return overloadedUsers.get(userNameLowered); + } + // END CODE + return super.getUser(userName); + } + + /** + * + * @return Collection of all users + */ + @Override + public Collection getUserList() { + final Collection overloadedList = new ArrayList(); + synchronized (getUsers()) { + final Collection normalList = getUsers().values(); + for (final User u : normalList) { + if (overloadedUsers.containsKey(u.getUUID().toLowerCase())) { + overloadedList.add(overloadedUsers.get(u.getUUID().toLowerCase())); + } else { + overloadedList.add(u); + } + } + } + return overloadedList; + } + + /** + * + * @param userId + * @return true if user is overloaded. + */ + public boolean isOverloaded(final String userId) { + return overloadedUsers.containsKey(userId.toLowerCase()); + } + + /** + * + * @param userId + */ + public void overloadUser(final String userId) { + if (!isOverloaded(userId)) { + User theUser = getUser(userId); + theUser = theUser.clone(); + if (overloadedUsers.containsKey(theUser.getUUID().toLowerCase())) { + overloadedUsers.remove(theUser.getUUID().toLowerCase()); + } + overloadedUsers.put(theUser.getUUID().toLowerCase(), theUser); + } + } + + @Override + public boolean removeGroup(final String groupName) { + if (groupName.equals(getDefaultGroup())) { + return false; + } + synchronized (getGroups()) { + for (final String key : getGroups().keySet()) { + if (groupName.equalsIgnoreCase(key)) { + getGroups().remove(key); + synchronized (getUsers()) { + for (final String userKey : getUsers().keySet()) { + final User user = getUsers().get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(getDefaultGroup()); + } + } + } + // OVERLOADED CODE + synchronized (overloadedUsers) { + for (final String userKey : overloadedUsers.keySet()) { + final User user = overloadedUsers.get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(getDefaultGroup()); + } + } + } + // END OVERLOAD + setGroupsChanged(true); + return true; + } + } + } + return false; + } + + /** + * + * @param userId + */ + public void removeOverload(final String userId) { + final User theUser = getUser(userId); + overloadedUsers.remove(theUser.getUUID().toLowerCase()); + } + + /** + * * @param userId * @return true if removed/false if not found. */ @Override - public boolean removeUser(String userId) { - + public boolean removeUser(final String userId) { // OVERLOADED CODE if (overloadedUsers.containsKey(userId.toLowerCase())) { overloadedUsers.remove(userId.toLowerCase()); @@ -103,118 +186,22 @@ public class OverloadedWorldHolder extends WorldDataHolder { return false; } - @Override - public boolean removeGroup(String groupName) { - - if (groupName.equals(getDefaultGroup())) { - return false; - } - synchronized (getGroups()) { - for (String key : getGroups().keySet()) { - if (groupName.equalsIgnoreCase(key)) { - getGroups().remove(key); - synchronized (getUsers()) { - for (String userKey : getUsers().keySet()) { - User user = getUsers().get(userKey); - if (user.getGroupName().equalsIgnoreCase(key)) { - user.setGroup(getDefaultGroup()); - } - - } - } - // OVERLOADED CODE - synchronized (overloadedUsers) { - for (String userKey : overloadedUsers.keySet()) { - User user = overloadedUsers.get(userKey); - if (user.getGroupName().equalsIgnoreCase(key)) { - user.setGroup(getDefaultGroup()); - } - - } - } - // END OVERLOAD - setGroupsChanged(true); - return true; - } - } - } - return false; - } - - /** - * - * @return Collection of all users - */ - @Override - public Collection getUserList() { - - Collection overloadedList = new ArrayList(); - synchronized (getUsers()) { - Collection normalList = getUsers().values(); - for (User u : normalList) { - if (overloadedUsers.containsKey(u.getUUID().toLowerCase())) { - overloadedList.add(overloadedUsers.get(u.getUUID().toLowerCase())); - } else { - overloadedList.add(u); - } - } - } - return overloadedList; - } - - /** - * - * @param userId - * @return true if user is overloaded. - */ - public boolean isOverloaded(String userId) { - - return overloadedUsers.containsKey(userId.toLowerCase()); - } - - /** - * - * @param userId - */ - public void overloadUser(String userId) { - - if (!isOverloaded(userId)) { - User theUser = getUser(userId); - theUser = theUser.clone(); - if (overloadedUsers.containsKey(theUser.getUUID().toLowerCase())) { - overloadedUsers.remove(theUser.getUUID().toLowerCase()); - } - overloadedUsers.put(theUser.getUUID().toLowerCase(), theUser); - } - } - - /** - * - * @param userId - */ - public void removeOverload(String userId) { - - User theUser = getUser(userId); - overloadedUsers.remove(theUser.getUUID().toLowerCase()); - } - /** * Gets the user in normal state. Surpassing the overload state. * It doesn't affect permissions. But it enables plugins change the * actual user permissions even in overload mode. - * + * * @param userId * @return user object */ - public User surpassOverload(String userId) { - + public User surpassOverload(final String userId) { if (!isOverloaded(userId)) { return getUser(userId); } if (getUsers().containsKey(userId.toLowerCase())) { return getUsers().get(userId.toLowerCase()); } - User newUser = createUser(userId); + final User newUser = createUser(userId); return newUser; } } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/dataholder/UsersDataHolder.java b/src/main/java/org/anjocaido/groupmanager/dataholder/UsersDataHolder.java index 255709b..48e7cba 100644 --- a/src/main/java/org/anjocaido/groupmanager/dataholder/UsersDataHolder.java +++ b/src/main/java/org/anjocaido/groupmanager/dataholder/UsersDataHolder.java @@ -9,17 +9,15 @@ import org.anjocaido.groupmanager.data.User; /** * This container holds all Users loaded from the relevant usersFile. - * + * * @author ElgarL - * + * */ public class UsersDataHolder { - private WorldDataHolder dataSource; private File usersFile; private boolean haveUsersChanged = false; private long timeStampUsers = 0; - /** * The actual groups holder */ @@ -29,32 +27,40 @@ public class UsersDataHolder { * Constructor */ protected UsersDataHolder() { - } - public void setDataSource(WorldDataHolder dataSource) { + public WorldDataHolder getDataSource() { + return this.dataSource; + } - this.dataSource = dataSource; - // push this data source to the users, so they pull the correct groups data. - synchronized (users) { - for (User user : users.values()) - user.setDataSource(this.dataSource); - } + /** + * @return the timeStampUsers + */ + public long getTimeStampUsers() { + return timeStampUsers; } /** * Note: Iteration over this object has to be synchronized! - * + * * @return the users */ public Map getUsers() { - return users; } - public WorldDataHolder getDataSource() { + /** + * @return the usersFile + */ + public File getUsersFile() { + return usersFile; + } - return this.dataSource; + /** + * @return the haveUsersChanged + */ + public boolean HaveUsersChanged() { + return haveUsersChanged; } /** @@ -64,55 +70,36 @@ public class UsersDataHolder { this.users.clear(); } - /** - * @return the usersFile - */ - public File getUsersFile() { - - return usersFile; - } - - /** - * @param usersFile - * the usersFile to set - */ - public void setUsersFile(File usersFile) { - - this.usersFile = usersFile; - } - - /** - * @return the haveUsersChanged - */ - public boolean HaveUsersChanged() { - - return haveUsersChanged; - } - - /** - * @param haveUsersChanged - * the haveUsersChanged to set - */ - public void setUsersChanged(boolean haveUsersChanged) { - - this.haveUsersChanged = haveUsersChanged; - } - - /** - * @return the timeStampUsers - */ - public long getTimeStampUsers() { - - return timeStampUsers; + public void setDataSource(final WorldDataHolder dataSource) { + this.dataSource = dataSource; + // push this data source to the users, so they pull the correct groups data. + synchronized (users) { + for (final User user : users.values()) + user.setDataSource(this.dataSource); + } } /** * @param timeStampUsers * the timeStampUsers to set */ - public void setTimeStampUsers(long timeStampUsers) { - + public void setTimeStampUsers(final long timeStampUsers) { this.timeStampUsers = timeStampUsers; } + /** + * @param haveUsersChanged + * the haveUsersChanged to set + */ + public void setUsersChanged(final boolean haveUsersChanged) { + this.haveUsersChanged = haveUsersChanged; + } + + /** + * @param usersFile + * the usersFile to set + */ + public void setUsersFile(final File usersFile) { + this.usersFile = usersFile; + } } diff --git a/src/main/java/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java b/src/main/java/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java index 0a9b52f..9e83432 100644 --- a/src/main/java/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java +++ b/src/main/java/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java @@ -46,7 +46,6 @@ import org.yaml.snakeyaml.reader.UnicodeReader; * @author gabrielcouto, ElgarL */ public class WorldDataHolder { - /** * World name */ @@ -70,7 +69,6 @@ public class WorldDataHolder { * @param worldName */ public WorldDataHolder(final String worldName) { - name = worldName; } @@ -82,11 +80,9 @@ public class WorldDataHolder { * @param users */ public WorldDataHolder(final String worldName, final GroupsDataHolder groups, final UsersDataHolder users) { - this.name = worldName; this.groups = groups; this.users = users; - // this.defaultGroup = defaultGroup; } @@ -101,16 +97,13 @@ public class WorldDataHolder { * @throws IOException */ public static WorldDataHolder load(final String worldName, final File groupsFile, final File usersFile) throws FileNotFoundException, IOException { - final WorldDataHolder ph = new WorldDataHolder(worldName); - GroupManager.setLoaded(false); if (groupsFile != null) loadGroups(ph, groupsFile); if (usersFile != null) loadUsers(ph, usersFile); GroupManager.setLoaded(true); - return ph; } @@ -130,7 +123,6 @@ public class WorldDataHolder { */ @Deprecated public static void reloadOldPlugins(final Server server) { - // Only reload permissions final PluginManager pm = server.getPluginManager(); final Plugin[] plugins = pm.getPlugins(); @@ -151,46 +143,34 @@ public class WorldDataHolder { * @param groupsFile */ public static void writeGroups(final WorldDataHolder ph, final File groupsFile) { - final Map root = new HashMap(); - final Map groupsMap = new HashMap(); - root.put("groups", groupsMap); synchronized (ph.getGroups()) { for (final String groupKey : ph.getGroups().keySet()) { final Group group = ph.getGroups().get(groupKey); - final Map aGroupMap = new HashMap(); groupsMap.put(group.getName(), aGroupMap); - if (ph.getDefaultGroup() == null) { GroupManager.logger.severe("There is no default group for world: " + ph.getName()); } aGroupMap.put("default", group.equals(ph.getDefaultGroup())); - final Map infoMap = new HashMap(); aGroupMap.put("info", infoMap); - for (final String infoKey : group.getVariables().getVarKeyList()) { infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); } - aGroupMap.put("inheritance", group.getInherits()); - aGroupMap.put("permissions", group.getPermissionList()); } } - if (!root.isEmpty()) { final DumperOptions opt = new DumperOptions(); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); final Yaml yaml = new Yaml(opt); try { final OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(groupsFile), "UTF-8"); - final String newLine = System.getProperty("line.separator"); - out.write("# Group inheritance" + newLine); out.write("#" + newLine); out.write("# Any inherited groups prefixed with a g: are global groups" + newLine); @@ -201,7 +181,6 @@ public class WorldDataHolder { out.write("#" + newLine); out.write("# Local group inheritances define your promotion tree when using 'manpromote/mandemote'" + newLine); out.write(newLine); - yaml.dump(root, out); out.close(); } catch (final UnsupportedEncodingException ex) { @@ -209,15 +188,12 @@ public class WorldDataHolder { } catch (final IOException e) { } } - // Update the LastModified time. ph.setGroupsFile(groupsFile); ph.setTimeStampGroups(groupsFile.lastModified()); ph.removeGroupsChangedFlag(); - if (GroupManager.isLoaded()) GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED); - /* * FileWriter tx = null; try { tx = new FileWriter(groupsFile, false); * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { } @@ -232,40 +208,31 @@ public class WorldDataHolder { * @param usersFile */ public static void writeUsers(final WorldDataHolder ph, final File usersFile) { - final Map root = new HashMap(); final LinkedHashMap usersMap = new LinkedHashMap(); - root.put("users", usersMap); synchronized (ph.getUsers()) { - // A sorted list of users. for (final String userKey : new TreeSet(ph.getUsers().keySet())) { final User user = ph.getUsers().get(userKey); if ((user.getGroup() == null || user.getGroup().equals(ph.getDefaultGroup())) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) { continue; } - final LinkedHashMap aUserMap = new LinkedHashMap(); usersMap.put(user.getUUID(), aUserMap); - if (!user.getUUID().equalsIgnoreCase(user.getLastName())) { aUserMap.put("lastname", user.getLastName()); } - // GROUP NODE if (user.getGroup() == null) { aUserMap.put("group", ph.getDefaultGroup().getName()); } else { aUserMap.put("group", user.getGroup().getName()); } - // SUBGROUPS NODE aUserMap.put("subgroups", user.subGroupListStringCopy()); - // PERMISSIONS NODE aUserMap.put("permissions", user.getPermissionList()); - // USER INFO NODE - BETA if (user.getVariables().getSize() > 0) { final Map infoMap = new HashMap(); @@ -275,10 +242,8 @@ public class WorldDataHolder { } } // END USER INFO NODE - BETA - } } - if (!root.isEmpty()) { final DumperOptions opt = new DumperOptions(); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); @@ -292,15 +257,12 @@ public class WorldDataHolder { } catch (final IOException e) { } } - // Update the LastModified time. ph.setUsersFile(usersFile); ph.setTimeStampUsers(usersFile.lastModified()); ph.removeUsersChangedFlag(); - if (GroupManager.isLoaded()) GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED); - /* * FileWriter tx = null; try { tx = new FileWriter(usersFile, false); * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { } @@ -319,12 +281,9 @@ public class WorldDataHolder { */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected static void loadGroups(final WorldDataHolder ph, final File groupsFile) throws FileNotFoundException, IOException { - // READ GROUPS FILE - final Yaml yamlGroups = new Yaml(new SafeConstructor()); Map groupsRootDataNode; - if (!groupsFile.exists()) { throw new IllegalArgumentException("The file which should contain groups does not exist!\n" + groupsFile.getPath()); } @@ -339,12 +298,9 @@ public class WorldDataHolder { } finally { groupsInputStream.close(); } - // PROCESS GROUPS FILE - final Map> inheritance = new HashMap>(); Map allGroupsNode = null; - /* * Fetch all groups under the 'groups' entry. */ @@ -353,20 +309,16 @@ public class WorldDataHolder { } catch (final Exception ex) { throw new IllegalArgumentException("Your " + groupsFile.getPath() + " file is invalid. See console for details.", ex); } - if (allGroupsNode == null) { throw new IllegalArgumentException("You have no groups in " + groupsFile.getPath() + "."); } - final Iterator groupItr = allGroupsNode.keySet().iterator(); String groupKey; Integer groupCount = 0; - /* * loop each group entry and process it's data. */ while (groupItr.hasNext()) { - try { groupCount++; // Attempt to fetch the next group name. @@ -374,36 +326,29 @@ public class WorldDataHolder { } catch (final Exception ex) { throw new IllegalArgumentException("Invalid group name for group entry (" + groupCount + ") in file: " + groupsFile.getPath(), ex); } - /* * Fetch this groups child nodes */ Map thisGroupNode = null; - try { thisGroupNode = (Map) allGroupsNode.get(groupKey); } catch (final Exception ex) { throw new IllegalArgumentException("Invalid child nodes for group '" + groupKey + "' in file: " + groupsFile.getPath(), ex); } - /* * Create a new group with this name in the assigned data source. */ final Group thisGrp = ph.createGroup(groupKey); - if (thisGrp == null) { throw new IllegalArgumentException("I think this Group was declared more than once: " + groupKey + " in file: " + groupsFile.getPath()); } - // DEFAULT NODE - Object nodeData = null; try { nodeData = thisGroupNode.get("default"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'permissions' for group: " + groupKey + " in file: " + groupsFile.getPath()); } - if (nodeData == null) { /* * If no 'default' node is found do nothing. @@ -419,16 +364,13 @@ public class WorldDataHolder { } ph.setDefaultGroup(thisGrp); } - // PERMISSIONS NODE - nodeData = null; try { nodeData = thisGroupNode.get("permissions"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'permissions' for '" + groupKey + "' in file: " + groupsFile.getPath()); } - if (nodeData == null) { /* * If no permissions node is found, or it's empty do nothing. @@ -449,7 +391,6 @@ public class WorldDataHolder { */ if (!o.toString().isEmpty()) thisGrp.addPermission(o.toString()); - } catch (final NullPointerException ex) { // Ignore this entry as it's null. It can be // safely dropped @@ -458,14 +399,12 @@ public class WorldDataHolder { } catch (final Exception ex) { throw new IllegalArgumentException("Invalid formatting found in 'permissions' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); } - } else if (nodeData instanceof String) { /* * Only add this permission if it's not empty. */ if (!nodeData.toString().isEmpty()) thisGrp.addPermission((String) nodeData); - } else { throw new IllegalArgumentException("Unknown type of 'permissions' node(Should be String or List) for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); } @@ -475,16 +414,13 @@ public class WorldDataHolder { */ thisGrp.sortPermissions(); } - // INFO NODE - nodeData = null; try { nodeData = thisGroupNode.get("info"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'info' section for group: " + groupKey + " in file: " + groupsFile.getPath()); } - if (nodeData == null) { /* * No info section was found, so leave all variables as @@ -492,7 +428,6 @@ public class WorldDataHolder { */ GroupManager.logger.warning("The group '" + thisGrp.getName() + "' has no 'info' section!"); GroupManager.logger.warning("Using default values: " + groupsFile.getPath()); - } else if (nodeData instanceof Map) { try { if (nodeData != null) { @@ -501,19 +436,15 @@ public class WorldDataHolder { } catch (final Exception ex) { throw new IllegalArgumentException("Invalid formatting found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); } - } else throw new IllegalArgumentException("Unknown entry found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); - // INHERITANCE NODE - nodeData = null; try { nodeData = thisGroupNode.get("inheritance"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'inheritance' section for group: " + groupKey + " in file: " + groupsFile.getPath()); } - if (nodeData == null || nodeData instanceof List) { if (nodeData == null) { /* @@ -521,7 +452,6 @@ public class WorldDataHolder { * nothing. */ } else if (nodeData instanceof List) { - try { for (final String grp : (List) nodeData) { if (inheritance.get(groupKey) == null) { @@ -529,23 +459,17 @@ public class WorldDataHolder { } inheritance.get(groupKey).add(grp); } - } catch (final Exception ex) { throw new IllegalArgumentException("Invalid formatting found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); } - } } else throw new IllegalArgumentException("Unknown entry found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); - // END GROUP - } - if (ph.getDefaultGroup() == null) { throw new IllegalArgumentException("There was no Default Group declared in file: " + groupsFile.getPath()); } - /* * Build the inheritance map and recored any errors */ @@ -563,12 +487,10 @@ public class WorldDataHolder { } } } - ph.removeGroupsChangedFlag(); // Update the LastModified time. ph.setGroupsFile(groupsFile); ph.setTimeStampGroups(groupsFile.lastModified()); - // return ph; } @@ -583,7 +505,6 @@ public class WorldDataHolder { */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected static void loadUsers(final WorldDataHolder ph, final File usersFile) throws FileNotFoundException, IOException { - // READ USERS FILE final Yaml yamlUsers = new Yaml(new SafeConstructor()); Map usersRootDataNode; @@ -601,11 +522,8 @@ public class WorldDataHolder { } finally { usersInputStream.close(); } - // PROCESS USERS FILE - Map allUsersNode = null; - /* * Fetch all child nodes under the 'users' entry. */ @@ -614,16 +532,12 @@ public class WorldDataHolder { } catch (final Exception ex) { throw new IllegalArgumentException("Your " + usersFile.getPath() + " file is invalid. See console for details.", ex); } - // Load users if the file is NOT empty - if (allUsersNode != null) { - final Iterator usersItr = allUsersNode.keySet().iterator(); String usersKey; Object node; Integer userCount = 0; - while (usersItr.hasNext()) { try { userCount++; @@ -633,49 +547,36 @@ public class WorldDataHolder { usersKey = Integer.toString((Integer) node); else usersKey = node.toString(); - } catch (final Exception ex) { throw new IllegalArgumentException("Invalid node type for user entry (" + userCount + ") in file: " + usersFile.getPath(), ex); } - Map thisUserNode = null; try { thisUserNode = (Map) allUsersNode.get(node); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found for user: " + usersKey + " in file: " + usersFile.getPath()); } - final User thisUser = ph.createUser(usersKey); if (thisUser == null) { throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey + " in file: " + usersFile.getPath()); } - // LASTNAME NODES - Object nodeData = null; try { - nodeData = thisUserNode.get("lastname"); - } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath()); } - if ((nodeData != null) && (nodeData instanceof String)) { - thisUser.setLastName((String) nodeData); - } - // USER PERMISSIONS NODES - nodeData = null; try { nodeData = thisUserNode.get("permissions"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'permissions' for user: " + usersKey + " in file: " + usersFile.getPath()); } - if (nodeData == null) { /* * If no permissions node is found, or it's empty do @@ -693,30 +594,25 @@ public class WorldDataHolder { } } } else if (nodeData instanceof String) { - /* * Only add this permission if it's not empty */ if (!nodeData.toString().isEmpty()) { thisUser.addPermission(nodeData.toString()); } - } } catch (final NullPointerException e) { // Ignore this entry as it's null. } thisUser.sortPermissions(); } - // SUBGROUPS NODES - nodeData = null; try { nodeData = thisUserNode.get("subgroups"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath()); } - if (nodeData == null) { /* * If no subgroups node is found, or it's empty do nothing. @@ -742,37 +638,29 @@ public class WorldDataHolder { GroupManager.logger.warning("Subgroup '" + nodeData.toString() + "' not found for user: " + thisUser.getLastName() + ". Ignoring entry in file: " + usersFile.getPath()); } } - // USER INFO NODE - nodeData = null; try { nodeData = thisUserNode.get("info"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'info' section for user: " + usersKey + " in file: " + usersFile.getPath()); } - if (nodeData == null) { /* * If no info node is found, or it's empty do nothing. */ } else if (nodeData instanceof Map) { thisUser.setVariables((Map) nodeData); - } else throw new IllegalArgumentException("Unknown entry found in 'info' section for user: " + thisUser.getLastName() + " in file: " + usersFile.getPath()); - // END INFO NODE - // PRIMARY GROUP - nodeData = null; try { nodeData = thisUserNode.get("group"); } catch (final Exception ex) { throw new IllegalArgumentException("Bad format found in 'group' section for user: " + usersKey + " in file: " + usersFile.getPath()); } - if (nodeData != null) { Group hisGroup = ph.getGroup(nodeData.toString()); if (hisGroup == null) { @@ -786,7 +674,6 @@ public class WorldDataHolder { } } } - ph.removeUsersChangedFlag(); // Update the LastModified time. ph.setUsersFile(usersFile); @@ -799,13 +686,11 @@ public class WorldDataHolder { * @param groupToAdd */ public void addGroup(Group groupToAdd) { - if (groupToAdd.getName().toLowerCase().startsWith("g:")) { GroupManager.getGlobalGroups().addGroup(groupToAdd); GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED); return; } - if (groupToAdd.getDataSource() != this) { groupToAdd = groupToAdd.clone(this); } @@ -823,7 +708,6 @@ public class WorldDataHolder { * the user you want to add to the permission list */ public void addUser(User theUser) { - if (theUser.getDataSource() != this) { theUser = theUser.clone(this); } @@ -848,16 +732,13 @@ public class WorldDataHolder { * @return null if group already exists. or new Group */ public Group createGroup(final String groupName) { - if (groupName.toLowerCase().startsWith("g:")) { final Group newGroup = new Group(groupName); return GroupManager.getGlobalGroups().newGroup(newGroup); } - if (getGroups().containsKey(groupName.toLowerCase())) { return null; } - final Group newGroup = new Group(this, groupName); addGroup(newGroup); setGroupsChanged(true); @@ -872,7 +753,6 @@ public class WorldDataHolder { * @return null if user already exists. or new User */ public User createUser(final String userId) { - if (getUsers().containsKey(userId.toLowerCase())) { return null; } @@ -889,7 +769,6 @@ public class WorldDataHolder { * @return the default group */ public Group getDefaultGroup() { - return groups.getDefaultGroup(); } @@ -911,7 +790,6 @@ public class WorldDataHolder { * @return a collection of the groups */ public Collection getGroupList() { - synchronized (getGroups()) { return new ArrayList(getGroups().values()); } @@ -923,7 +801,6 @@ public class WorldDataHolder { * @return the groups */ public Map getGroups() { - return groups.getGroups(); } @@ -931,7 +808,6 @@ public class WorldDataHolder { * @return the groupsFile */ public File getGroupsFile() { - return groups.getGroupsFile(); } @@ -939,7 +815,6 @@ public class WorldDataHolder { * @return the groups */ public GroupsDataHolder getGroupsObject() { - return groups; } @@ -947,7 +822,6 @@ public class WorldDataHolder { * @return the name */ public String getName() { - return name; } @@ -955,7 +829,6 @@ public class WorldDataHolder { * @return the permissionsHandler */ public AnjoPermissionsHandler getPermissionsHandler() { - if (permissionsHandler == null) { permissionsHandler = new AnjoPermissionsHandler(this); } @@ -966,7 +839,6 @@ public class WorldDataHolder { * @return the timeStampGroups */ public long getTimeStampGroups() { - return groups.getTimeStampGroups(); } @@ -974,7 +846,6 @@ public class WorldDataHolder { * @return the timeStampUsers */ public long getTimeStampUsers() { - return users.getTimeStampUsers(); } @@ -987,27 +858,20 @@ public class WorldDataHolder { * @return class that manage that user permission */ public User getUser(final String userId) { - if (getUsers().containsKey(userId.toLowerCase())) { return getUsers().get(userId.toLowerCase()); } - // Legacy name matching if (userId.length() < 36) { - // Search for a LastName match for (final User user : getUserList()) { - if (user.getLastName().equalsIgnoreCase(userId)) { return user; } } - } - // No user account found so create a new one. final User newUser = createUser(userId); - return newUser; } @@ -1022,38 +886,26 @@ public class WorldDataHolder { * @return the user object for this player. */ public User getUser(final String uUID, final String currentName) { - // Check for a UUID account User user = getUsers().get(uUID.toLowerCase()); - if (user != null) { - user.setLastName(currentName); return user; - } - // Search for a LastName match for (final User usr : getUserList()) { - if (usr.getLastName().equalsIgnoreCase(currentName) && usr.getUUID().equalsIgnoreCase(usr.getLastName())) { - // Clone this user so we can set it's uUID user = usr.clone(uUID, currentName); - // Delete it and replace with the new clone. this.removeUser(usr.getUUID()); this.addUser(user); - return getUsers().get(uUID.toLowerCase()); } - } - // No user account found so create a new one. final User newUser = createUser(uUID); newUser.setLastName(currentName); - return newUser; } @@ -1062,7 +914,6 @@ public class WorldDataHolder { * @return a collection of the users */ public Collection getUserList() { - synchronized (getUsers()) { return new ArrayList(getUsers().values()); } @@ -1074,7 +925,6 @@ public class WorldDataHolder { * @return the users */ public Map getUsers() { - return users.getUsers(); } @@ -1082,7 +932,6 @@ public class WorldDataHolder { * @return the usersFile */ public File getUsersFile() { - return users.getUsersFile(); } @@ -1090,7 +939,6 @@ public class WorldDataHolder { * @return the users */ public UsersDataHolder getUsersObject() { - return users; } @@ -1113,7 +961,6 @@ public class WorldDataHolder { * @return true if any group data has changed. */ public boolean haveGroupsChanged() { - if (groups.HaveGroupsChanged()) { return true; } @@ -1132,7 +979,6 @@ public class WorldDataHolder { * @return true if any user data has changed */ public boolean haveUsersChanged() { - if (users.HaveUsersChanged()) { return true; } @@ -1152,12 +998,10 @@ public class WorldDataHolder { * @return true if we have data for this player. */ public boolean isUserDeclared(final String userId) { - return getUsers().containsKey(userId.toLowerCase()); } public void loadGroups(final File groupsFile) { - GroupManager.setLoaded(false); try { setGroupsFile(groupsFile); @@ -1169,12 +1013,10 @@ public class WorldDataHolder { e.printStackTrace(); throw new IllegalArgumentException("Error accessing the groups file!\n" + groupsFile.getPath()); } - GroupManager.setLoaded(true); } public void loadUsers(final File usersFile) { - GroupManager.setLoaded(false); try { setUsersFile(usersFile); @@ -1186,7 +1028,6 @@ public class WorldDataHolder { e.printStackTrace(); throw new IllegalArgumentException("Error accessing the users file!\n" + usersFile.getPath()); } - GroupManager.setLoaded(true); } @@ -1194,7 +1035,6 @@ public class WorldDataHolder { * reads the file again */ public void reload() { - try { reloadGroups(); reloadUsers(); @@ -1207,12 +1047,10 @@ public class WorldDataHolder { * Refresh Group data from file */ public void reloadGroups() { - GroupManager.setLoaded(false); try { // temporary holder in case the load fails. WorldDataHolder ph = new WorldDataHolder(this.getName()); - loadGroups(ph, getGroupsFile()); // transfer new data resetGroups(); @@ -1222,7 +1060,6 @@ public class WorldDataHolder { this.setDefaultGroup(getGroup(ph.getDefaultGroup().getName())); this.removeGroupsChangedFlag(); this.setTimeStampGroups(getGroupsFile().lastModified()); - ph = null; } catch (final Exception ex) { Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex); @@ -1235,7 +1072,6 @@ public class WorldDataHolder { * Refresh Users data from file */ public void reloadUsers() { - GroupManager.setLoaded(false); try { // temporary holder in case the load fails. @@ -1254,7 +1090,6 @@ public class WorldDataHolder { } this.removeUsersChangedFlag(); this.setTimeStampUsers(getUsersFile().lastModified()); - ph = null; } catch (final Exception ex) { Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex); @@ -1271,11 +1106,9 @@ public class WorldDataHolder { * non-existant */ public boolean removeGroup(final String groupName) { - if (groupName.toLowerCase().startsWith("g:")) { return GroupManager.getGlobalGroups().removeGroup(groupName); } - if (getDefaultGroup() != null && groupName.equalsIgnoreCase(getDefaultGroup().getName())) { return false; } @@ -1287,14 +1120,12 @@ public class WorldDataHolder { return true; } return false; - } /** * */ public void removeGroupsChangedFlag() { - setGroupsChanged(false); synchronized (getGroups()) { for (final Group g : getGroups().values()) { @@ -1311,7 +1142,6 @@ public class WorldDataHolder { * @return true if it had something to remove */ public boolean removeUser(final String userId) { - if (getUsers().containsKey(userId.toLowerCase())) { getUsers().remove(userId.toLowerCase()); setUsersChanged(true); @@ -1326,7 +1156,6 @@ public class WorldDataHolder { * */ public void removeUsersChangedFlag() { - setUsersChanged(false); synchronized (getUsers()) { for (final User u : getUsers().values()) { @@ -1339,7 +1168,6 @@ public class WorldDataHolder { * Resets Groups. */ public void resetGroups() { - // setDefaultGroup(null); groups.resetGroups(); } @@ -1348,7 +1176,6 @@ public class WorldDataHolder { * Resets Users */ public void resetUsers() { - users.resetUsers(); } @@ -1359,7 +1186,6 @@ public class WorldDataHolder { * the group you want make default. */ public void setDefaultGroup(final Group group) { - if (!getGroups().containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) { addGroup(group); } @@ -1374,7 +1200,6 @@ public class WorldDataHolder { * the haveGroupsChanged to set */ public void setGroupsChanged(final boolean setGroupsChanged) { - groups.setGroupsChanged(setGroupsChanged); } @@ -1383,7 +1208,6 @@ public class WorldDataHolder { * the groupsFile to set */ public void setGroupsFile(final File file) { - groups.setGroupsFile(file); } @@ -1392,12 +1216,10 @@ public class WorldDataHolder { * the GroupsDataHolder to set */ public void setGroupsObject(final GroupsDataHolder groupsDataHolder) { - groups = groupsDataHolder; } public void setTimeStamps() { - if (getGroupsFile() != null) setTimeStampGroups(getGroupsFile().lastModified()); if (getUsersFile() != null) @@ -1409,7 +1231,6 @@ public class WorldDataHolder { * the haveUsersChanged to set */ public void setUsersChanged(final boolean haveUsersChanged) { - users.setUsersChanged(haveUsersChanged); } @@ -1418,7 +1239,6 @@ public class WorldDataHolder { * the usersFile to set */ public void setUsersFile(final File file) { - users.setUsersFile(file); } @@ -1427,7 +1247,6 @@ public class WorldDataHolder { * the UsersDataHolder to set */ public void setUsersObject(final UsersDataHolder usersDataHolder) { - users = usersDataHolder; } @@ -1437,7 +1256,6 @@ public class WorldDataHolder { * This should be called whenever a set of world data is fetched. */ public void updateDataSource() { - this.groups.setDataSource(this); this.users.setDataSource(this); } @@ -1447,7 +1265,6 @@ public class WorldDataHolder { * the timeStampGroups to set */ protected void setTimeStampGroups(final long timeStampGroups) { - groups.setTimeStampGroups(timeStampGroups); } @@ -1456,8 +1273,6 @@ public class WorldDataHolder { * the timeStampUsers to set */ protected void setTimeStampUsers(final long timeStampUsers) { - users.setTimeStampUsers(timeStampUsers); } - } diff --git a/src/main/java/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java b/src/main/java/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java index 6742406..ffc3ac8 100644 --- a/src/main/java/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java +++ b/src/main/java/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java @@ -16,54 +16,129 @@ import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; + import org.anjocaido.groupmanager.GroupManager; -import org.anjocaido.groupmanager.dataholder.WorldDataHolder; import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; import org.anjocaido.groupmanager.utils.Tasks; import org.bukkit.World; import org.bukkit.entity.Player; /** - * + * * @author gabrielcouto */ public class WorldsHolder { - /** * Map with instances of loaded worlds. */ private Map worldsData = new HashMap(); - /** * Map of mirrors: * The key is the mirror. * The object is the mirrored. - * + * * Mirror shows the same data of mirrored. */ private Map mirrorsGroup = new HashMap(); private Map mirrorsUser = new HashMap(); - private String serverDefaultWorldName; - private GroupManager plugin; + private final GroupManager plugin; private File worldsFolder; /** - * + * * @param plugin */ - public WorldsHolder(GroupManager plugin) { - + public WorldsHolder(final GroupManager plugin) { this.plugin = plugin; resetWorldsHolder(); } + /** + * Returns all physically loaded worlds which have at least one of their own + * data sets for users or groups which isn't an identical mirror. + * + * @return ArrayList of all loaded worlds + */ + public ArrayList allWorldsDataList() { + final ArrayList list = new ArrayList(); + for (final String world : worldsData.keySet()) { + if (!world.equalsIgnoreCase("all_unnamed_worlds")) { + // Fetch the relevant world object + OverloadedWorldHolder data = getWorldData(world); + if (!list.contains(data)) { + final String worldNameLowered = data.getName().toLowerCase(); + final String usersMirror = mirrorsUser.get(worldNameLowered); + final String groupsMirror = mirrorsGroup.get(worldNameLowered); + // is users mirrored? + if (usersMirror != null) { + // If both are mirrored + if (groupsMirror != null) { + // if the data sources are the same, return the parent + if (usersMirror == groupsMirror) { + data = getWorldData(usersMirror.toLowerCase()); + // Only add the parent if it's not already listed. + if (!list.contains(data)) + list.add(data); + continue; + } + // Both data sources are mirrors, but they are from different parents + // so fall through to add the actual data object. + } + // Groups isn't a mirror so fall through to add this this worlds data source + } + // users isn't mirrored so we need to add this worlds data source + list.add(data); + } + } + } + return list; + } + + /** + * Copies the specified world data to another world + * + * @param fromWorld + * @param toWorld + * @return true if successfully copied. + */ + public boolean cloneWorld(final String fromWorld, final String toWorld) { + final File fromWorldFolder = new File(worldsFolder, fromWorld.toLowerCase()); + final File toWorldFolder = new File(worldsFolder, toWorld.toLowerCase()); + if (toWorldFolder.exists() || !fromWorldFolder.exists()) { + return false; + } + final File fromWorldGroups = new File(fromWorldFolder, "groups.yml"); + final File fromWorldUsers = new File(fromWorldFolder, "users.yml"); + if (!fromWorldGroups.exists() || !fromWorldUsers.exists()) { + return false; + } + final File toWorldGroups = new File(toWorldFolder, "groups.yml"); + final File toWorldUsers = new File(toWorldFolder, "users.yml"); + toWorldFolder.mkdirs(); + try { + Tasks.copy(fromWorldGroups, toWorldGroups); + Tasks.copy(fromWorldUsers, toWorldUsers); + } catch (final IOException ex) { + Logger.getLogger(WorldsHolder.class.getName()).log(Level.SEVERE, null, ex); + return false; + } + return true; + } + + /** + * @return the defaultWorld + */ + public OverloadedWorldHolder getDefaultWorld() { + return getUpdatedWorldData(serverDefaultWorldName); + } + /** * @return the mirrorsGroup */ public Map getMirrorsGroup() { - return mirrorsGroup; } @@ -71,187 +146,259 @@ public class WorldsHolder { * @return the mirrorsUser */ public Map getMirrorsUser() { - return mirrorsUser; } - public boolean isWorldKnown(String name) { + /** + * Retrieves the field player.getWorld().getName() and do + * getWorld(worldName) + * + * @param player + * @return OverloadedWorldHolder + */ + public OverloadedWorldHolder getWorldData(final Player player) { + return getWorldData(player.getWorld().getName()); + } + /** + * Returns the dataHolder for the given world. + * If the world is not on the worlds list, returns the default world + * holder. + * + * Mirrors return their parent world data. + * If no mirroring data it returns the default world. + * + * @param worldName + * @return OverloadedWorldHolder + */ + public OverloadedWorldHolder getWorldData(final String worldName) { + final String worldNameLowered = worldName.toLowerCase(); + // Find this worlds data + if (worldsData.containsKey(worldNameLowered)) + return getUpdatedWorldData(worldNameLowered); + // Oddly no data source was found for this world so attempt to return the global mirror. + if (worldsData.containsKey("all_unnamed_worlds")) { + GroupManager.logger.finest("加载世界 " + worldName + " 时未找到或配置错误. 返回 all_unnamed_worlds 配置..."); + return getUpdatedWorldData("all_unnamed_worlds"); + } + // Oddly no data source or global mirror was found for this world so return the default. + GroupManager.logger.finest("加载世界 " + worldName + " 时未找到或配置错误. 返回默认世界..."); + return getDefaultWorld(); + } + + /** + * Do a matching of playerName, if its found only one player, do + * getWorldData(player) + * + * @param playerName + * @return null if matching returned no player, or more than one. + */ + public OverloadedWorldHolder getWorldDataByPlayerName(final String playerName) { + final List matchPlayer = plugin.getServer().matchPlayer(playerName); + if (matchPlayer.size() == 1) { + return getWorldData(matchPlayer.get(0)); + } + return null; + } + + /** + * Returns the PermissionsHandler for this player data + * + * @param player + * @return AnjoPermissionsHandler + */ + public AnjoPermissionsHandler getWorldPermissions(final Player player) { + return getWorldData(player).getPermissionsHandler(); + } + + /** + * It does getWorld(worldName).getPermissionsHandler() + * + * @param worldName + * @return AnjoPermissionsHandler + */ + public AnjoPermissionsHandler getWorldPermissions(final String worldName) { + return getWorldData(worldName).getPermissionsHandler(); + } + + /** + * Id does getWorldDataByPlayerName(playerName). + * If it doesnt return null, it will return result.getPermissionsHandler() + * + * @param playerName + * @return null if the player matching gone wrong. + */ + public AnjoPermissionsHandler getWorldPermissionsByPlayerName(final String playerName) { + final WorldDataHolder dh = getWorldDataByPlayerName(playerName); + if (dh != null) { + return dh.getPermissionsHandler(); + } + return null; + } + + /** + * Verify if world has it's own file permissions. + * + * @param worldName + * @return true if it has its own holder. false if not. + */ + public boolean hasOwnData(final String worldName) { + if (worldsData.containsKey(worldName.toLowerCase()) && (!mirrorsGroup.containsKey(worldName.toLowerCase()) || !mirrorsUser.containsKey(worldName.toLowerCase()))) { + return true; + } + return false; + } + + /** + * Tells if the such world has been mapped. + * + * It will return true if world is a mirror. + * + * @param worldName + * @return true if world is loaded or mirrored. false if not listed + */ + public boolean isInList(final String worldName) { + if (worldsData.containsKey(worldName.toLowerCase()) || mirrorsGroup.containsKey(worldName.toLowerCase()) || mirrorsUser.containsKey(worldName.toLowerCase())) { + return true; + } + return false; + } + + public boolean isWorldKnown(final String name) { return worldsData.containsKey(name.toLowerCase()); } - public void resetWorldsHolder() { - - worldsData = new HashMap(); - mirrorsGroup = new HashMap(); - mirrorsUser = new HashMap(); - - // Setup folders and check files exist for the primary world - verifyFirstRun(); - initialLoad(); - if (serverDefaultWorldName == null) - throw new IllegalStateException("There is no default group! OMG!"); + /** + * Wrapper for LoadWorld(String,Boolean) for backwards compatibility + * + * Load a world from file. + * If it already been loaded, summon reload method from dataHolder. + * + * @param worldName + */ + public void loadWorld(final String worldName) { + loadWorld(worldName, false); } - private void initialLoad() { - - // load the initial world - initialWorldLoading(); - // Configure and load any mirrors and additional worlds as defined in config.yml - mirrorSetUp(); - // search the worlds folder for any manually created worlds (not listed in config.yml) - loadAllSearchedWorlds(); - } - - private void initialWorldLoading() { - - // Load the default world - loadWorld(serverDefaultWorldName); - // defaultWorld = getUpdatedWorldData(serverDefaultWorldName); - } - - private void loadAllSearchedWorlds() { - - /* - * Read all known worlds from Bukkit Create the data files if they don't - * already exist, and they are not mirrored. - */ - for (World world : plugin.getServer().getWorlds()) { - GroupManager.logger.log(Level.FINE, "Checking data for " + world.getName() + "."); - if ((!worldsData.containsKey(world.getName().toLowerCase())) && ((!mirrorsGroup.containsKey(world.getName().toLowerCase())) || (!mirrorsUser.containsKey(world.getName().toLowerCase())))) { - - if (worldsData.containsKey("all_unnamed_worlds")) { - - String usersMirror = mirrorsUser.get("all_unnamed_worlds"); - String groupsMirror = mirrorsGroup.get("all_unnamed_worlds"); - - if (usersMirror != null) - mirrorsUser.put(world.getName().toLowerCase(), usersMirror); - - if (groupsMirror != null) - mirrorsGroup.put(world.getName().toLowerCase(), groupsMirror); - - } - - GroupManager.logger.log(Level.FINE, "Creating folders for " + world.getName() + "."); - setupWorldFolder(world.getName()); - } + /** + * Load a world from file. + * If it already been loaded, summon reload method from dataHolder. + * + * @param worldName + */ + public void loadWorld(final String worldName, final Boolean isMirror) { + final String worldNameLowered = worldName.toLowerCase(); + if (worldsData.containsKey(worldNameLowered)) { + worldsData.get(worldNameLowered).reload(); + return; } - /* - * Loop over all folders within the worlds folder and attempt to load - * the world data - */ - for (File folder : worldsFolder.listFiles()) { - if (folder.isDirectory() && !folder.getName().startsWith(".")) { - GroupManager.logger.info("World Found: " + folder.getName()); - - /* - * don't load any worlds which are already loaded or fully - * mirrored worlds that don't need data. - */ - if (!worldsData.containsKey(folder.getName().toLowerCase()) && ((!mirrorsGroup.containsKey(folder.getName().toLowerCase())) || (!mirrorsUser.containsKey(folder.getName().toLowerCase())))) { - /* - * Call setupWorldFolder to check case sensitivity and - * convert to lower case, before we attempt to load this - * world. - */ - setupWorldFolder(folder.getName()); - loadWorld(folder.getName().toLowerCase()); - } - + GroupManager.logger.finest("Trying to load world " + worldName + "..."); + final File thisWorldFolder = new File(worldsFolder, worldNameLowered); + if ((isMirror) || (thisWorldFolder.exists() && thisWorldFolder.isDirectory())) { + // Setup file handles, if not mirrored + final File groupsFile = (mirrorsGroup.containsKey(worldNameLowered)) ? null : new File(thisWorldFolder, "groups.yml"); + final File usersFile = (mirrorsUser.containsKey(worldNameLowered)) ? null : new File(thisWorldFolder, "users.yml"); + if ((groupsFile != null) && (!groupsFile.exists())) { + throw new IllegalArgumentException("世界 '" + worldName + "' 的组配置文件未找到: " + groupsFile.getPath()); } + if ((usersFile != null) && (!usersFile.exists())) { + throw new IllegalArgumentException("世界 '" + worldName + "' 的用户配置文件未找到: " + usersFile.getPath()); + } + WorldDataHolder tempHolder = new WorldDataHolder(worldNameLowered); + // Map the group object for any mirror + if (mirrorsGroup.containsKey(worldNameLowered)) + tempHolder.setGroupsObject(this.getWorldData(mirrorsGroup.get(worldNameLowered)).getGroupsObject()); + else + tempHolder.loadGroups(groupsFile); + // Map the user object for any mirror + if (mirrorsUser.containsKey(worldNameLowered)) + tempHolder.setUsersObject(this.getWorldData(mirrorsUser.get(worldNameLowered)).getUsersObject()); + else + tempHolder.loadUsers(usersFile); + final OverloadedWorldHolder thisWorldData = new OverloadedWorldHolder(tempHolder); + // null the object so we don't keep file handles open where we shouldn't + tempHolder = null; + // Set the file TimeStamps as it will be default from the initial load. + thisWorldData.setTimeStamps(); + if (thisWorldData != null) { + GroupManager.logger.finest("成功载入世界 " + worldName + "..."); + worldsData.put(worldNameLowered, thisWorldData); + return; + } + // GroupManager.logger.severe("Failed to load world " + worldName + "..."); } } @SuppressWarnings("rawtypes") public void mirrorSetUp() { - mirrorsGroup.clear(); mirrorsUser.clear(); - Map mirrorsMap = plugin.getGMConfig().getMirrorsMap(); - - HashSet mirroredWorlds = new HashSet(); - + final Map mirrorsMap = plugin.getGMConfig().getMirrorsMap(); + final HashSet mirroredWorlds = new HashSet(); if (mirrorsMap != null) { - for (String source : mirrorsMap.keySet()) { + for (final String source : mirrorsMap.keySet()) { // Make sure all non mirrored worlds have a set of data files. setupWorldFolder(source); // Load the world data if (!worldsData.containsKey(source.toLowerCase())) loadWorld(source); - if (mirrorsMap.get(source) instanceof ArrayList) { - ArrayList mirrorList = (ArrayList) mirrorsMap.get(source); - + final ArrayList mirrorList = (ArrayList) mirrorsMap.get(source); // These worlds fully mirror their parent - for (Object o : mirrorList) { - String world = o.toString().toLowerCase(); + for (final Object o : mirrorList) { + final String world = o.toString().toLowerCase(); if (!world.equalsIgnoreCase(serverDefaultWorldName)) { try { mirrorsGroup.remove(world); mirrorsUser.remove(world); - } catch (Exception e) { + } catch (final Exception e) { } mirrorsGroup.put(world, getWorldData(source).getName()); mirrorsUser.put(world, getWorldData(source).getName()); - // Track this world so we can create a datasource for it later mirroredWorlds.add(o.toString()); - } else - GroupManager.logger.log(Level.WARNING, "Mirroring error with " + o.toString() + ". Recursive loop detected!"); + GroupManager.logger.log(Level.WARNING, "镜像错误 " + o.toString() + ". 检测到递归循环!"); } } else if (mirrorsMap.get(source) instanceof Map) { - Map subSection = (Map) mirrorsMap.get(source); - - for (Object key : subSection.keySet()) { - + final Map subSection = (Map) mirrorsMap.get(source); + for (final Object key : subSection.keySet()) { if (!((String) key).equalsIgnoreCase(serverDefaultWorldName)) { - if (subSection.get(key) instanceof ArrayList) { - ArrayList mirrorList = (ArrayList) subSection.get(key); - + final ArrayList mirrorList = (ArrayList) subSection.get(key); // These worlds have defined mirroring - for (Object o : mirrorList) { - String type = o.toString().toLowerCase(); + for (final Object o : mirrorList) { + final String type = o.toString().toLowerCase(); try { if (type.equals("groups")) mirrorsGroup.remove(((String) key).toLowerCase()); - if (type.equals("users")) mirrorsUser.remove(((String) key).toLowerCase()); - - } catch (Exception e) { + } catch (final Exception e) { } if (type.equals("groups")) { mirrorsGroup.put(((String) key).toLowerCase(), getWorldData(source).getName()); - GroupManager.logger.log(Level.FINE, "Adding groups mirror for " + key + "."); + GroupManager.logger.log(Level.FINE, "添加组镜像 " + key + "."); } - if (type.equals("users")) { mirrorsUser.put(((String) key).toLowerCase(), getWorldData(source).getName()); - GroupManager.logger.log(Level.FINE, "Adding users mirror for " + key + "."); + GroupManager.logger.log(Level.FINE, "添加用户镜像 " + key + "."); } } - // Track this world so we can create a datasource for it later mirroredWorlds.add((String) key); - } else - throw new IllegalStateException("Unknown mirroring format for " + (String) key); - + throw new IllegalStateException("位置的镜像格式 " + (String) key); } else { - GroupManager.logger.log(Level.WARNING, "Mirroring error with " + (String) key + ". Recursive loop detected!"); + GroupManager.logger.log(Level.WARNING, "镜像错误 " + (String) key + ". 检测到递归循环!"); } - } } } - // Create a datasource for any worlds not already loaded - for (String world : mirroredWorlds) { + for (final String world : mirroredWorlds) { if (!worldsData.containsKey(world.toLowerCase())) { - GroupManager.logger.log(Level.FINE, "No data for " + world + "."); + GroupManager.logger.log(Level.FINE, "世界 " + world + " 没有数据."); setupWorldFolder(world); loadWorld(world, true); } @@ -263,12 +410,10 @@ public class WorldsHolder { * */ public void reloadAll() { - // Load global groups GroupManager.getGlobalGroups().load(); - - ArrayList alreadyDone = new ArrayList(); - for (WorldDataHolder w : worldsData.values()) { + final ArrayList alreadyDone = new ArrayList(); + for (final WorldDataHolder w : worldsData.values()) { if (alreadyDone.contains(w)) { continue; } @@ -276,58 +421,62 @@ public class WorldsHolder { w.reloadGroups(); if (!mirrorsUser.containsKey(w.getName().toLowerCase())) w.reloadUsers(); - alreadyDone.add(w); } - } /** - * + * * @param worldName */ - public void reloadWorld(String worldName) { - + public void reloadWorld(final String worldName) { if (!mirrorsGroup.containsKey(worldName.toLowerCase())) getWorldData(worldName).reloadGroups(); if (!mirrorsUser.containsKey(worldName.toLowerCase())) getWorldData(worldName).reloadUsers(); } + public void resetWorldsHolder() { + worldsData = new HashMap(); + mirrorsGroup = new HashMap(); + mirrorsUser = new HashMap(); + // Setup folders and check files exist for the primary world + verifyFirstRun(); + initialLoad(); + if (serverDefaultWorldName == null) + throw new IllegalStateException("当前没有默认组! OMG!"); + } + /** * Wrapper to retain backwards compatibility * (call this function to auto overwrite files) */ public void saveChanges() { - saveChanges(true); } /** * */ - public boolean saveChanges(boolean overwrite) { - + public boolean saveChanges(final boolean overwrite) { boolean changed = false; - ArrayList alreadyDone = new ArrayList(); + final ArrayList alreadyDone = new ArrayList(); Tasks.removeOldFiles(plugin, plugin.getBackupFolder()); - // Write Global Groups if (GroupManager.getGlobalGroups().haveGroupsChanged()) { GroupManager.getGlobalGroups().writeGroups(overwrite); } else { if (GroupManager.getGlobalGroups().getTimeStampGroups() < GroupManager.getGlobalGroups().getGlobalGroupsFile().lastModified()) { - System.out.print("Newer GlobalGroups file found (Loading changes)!"); + System.out.print("发现新的全局组配置 (载入数据)!"); GroupManager.getGlobalGroups().load(); } } - - for (OverloadedWorldHolder w : worldsData.values()) { + for (final OverloadedWorldHolder w : worldsData.values()) { if (alreadyDone.contains(w)) { continue; } if (w == null) { - GroupManager.logger.severe("WHAT HAPPENED?"); + GroupManager.logger.severe("发生了什么!?"); continue; } if (!mirrorsGroup.containsKey(w.getName().toLowerCase())) @@ -335,7 +484,6 @@ public class WorldsHolder { if (overwrite || (!overwrite && (w.getTimeStampGroups() >= w.getGroupsFile().lastModified()))) { // Backup Groups file backupFile(w, true); - WorldDataHolder.writeGroups(w, w.getGroupsFile()); changed = true; // w.removeGroupsChangedFlag(); @@ -347,7 +495,7 @@ public class WorldsHolder { } else { // Check for newer file as no local changes. if (w.getTimeStampGroups() < w.getGroupsFile().lastModified()) { - System.out.print("Newer Groups file found (Loading changes)!"); + System.out.print("发现新的组配置 (载入数据)!"); // Backup Groups file backupFile(w, true); w.reloadGroups(); @@ -359,7 +507,6 @@ public class WorldsHolder { if (overwrite || (!overwrite && (w.getTimeStampUsers() >= w.getUsersFile().lastModified()))) { // Backup Users file backupFile(w, false); - WorldDataHolder.writeUsers(w, w.getUsersFile()); changed = true; // w.removeUsersChangedFlag(); @@ -371,7 +518,7 @@ public class WorldsHolder { } else { // Check for newer file as no local changes. if (w.getTimeStampUsers() < w.getUsersFile().lastModified()) { - System.out.print("Newer Users file found (Loading changes)!"); + System.out.print("发现新的用户配置 (载入数据)!"); // Backup Users file backupFile(w, false); w.reloadUsers(); @@ -383,176 +530,18 @@ public class WorldsHolder { return changed; } - /** - * Backup the Groups/Users file - * - * @param w - * @param groups - */ - private void backupFile(OverloadedWorldHolder w, Boolean groups) { - - File backupFile = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + (groups ? "_g_" : "_u_") + Tasks.getDateString() + ".yml"); - try { - Tasks.copy((groups ? w.getGroupsFile() : w.getUsersFile()), backupFile); - } catch (IOException ex) { - GroupManager.logger.log(Level.SEVERE, null, ex); - } - } - - /** - * Returns the dataHolder for the given world. - * If the world is not on the worlds list, returns the default world - * holder. - * - * Mirrors return their parent world data. - * If no mirroring data it returns the default world. - * - * @param worldName - * @return OverloadedWorldHolder - */ - public OverloadedWorldHolder getWorldData(String worldName) { - - String worldNameLowered = worldName.toLowerCase(); - - // Find this worlds data - if (worldsData.containsKey(worldNameLowered)) - return getUpdatedWorldData(worldNameLowered); - - // Oddly no data source was found for this world so attempt to return the global mirror. - if (worldsData.containsKey("all_unnamed_worlds")) { - GroupManager.logger.finest("Requested world " + worldName + " not found or badly mirrored. Returning all_unnamed_worlds world..."); - return getUpdatedWorldData("all_unnamed_worlds"); - } - - // Oddly no data source or global mirror was found for this world so return the default. - GroupManager.logger.finest("Requested world " + worldName + " not found or badly mirrored. Returning default world..."); - return getDefaultWorld(); - } - - /** - * Get the requested world data and update it's dataSource to be relevant - * for this world - * - * @param worldName - * @return updated world holder - */ - private OverloadedWorldHolder getUpdatedWorldData(String worldName) { - - String worldNameLowered = worldName.toLowerCase(); - - if (worldsData.containsKey(worldNameLowered)) { - OverloadedWorldHolder data = worldsData.get(worldNameLowered); - data.updateDataSource(); - return data; - } - return null; - - } - - /** - * Do a matching of playerName, if its found only one player, do - * getWorldData(player) - * - * @param playerName - * @return null if matching returned no player, or more than one. - */ - public OverloadedWorldHolder getWorldDataByPlayerName(String playerName) { - - List matchPlayer = plugin.getServer().matchPlayer(playerName); - if (matchPlayer.size() == 1) { - return getWorldData(matchPlayer.get(0)); - } - return null; - } - - /** - * Retrieves the field player.getWorld().getName() and do - * getWorld(worldName) - * - * @param player - * @return OverloadedWorldHolder - */ - public OverloadedWorldHolder getWorldData(Player player) { - - return getWorldData(player.getWorld().getName()); - } - - /** - * It does getWorld(worldName).getPermissionsHandler() - * - * @param worldName - * @return AnjoPermissionsHandler - */ - public AnjoPermissionsHandler getWorldPermissions(String worldName) { - - return getWorldData(worldName).getPermissionsHandler(); - } - - /** - * Returns the PermissionsHandler for this player data - * - * @param player - * @return AnjoPermissionsHandler - */ - public AnjoPermissionsHandler getWorldPermissions(Player player) { - - return getWorldData(player).getPermissionsHandler(); - } - - /** - * Id does getWorldDataByPlayerName(playerName). - * If it doesnt return null, it will return result.getPermissionsHandler() - * - * @param playerName - * @return null if the player matching gone wrong. - */ - public AnjoPermissionsHandler getWorldPermissionsByPlayerName(String playerName) { - - WorldDataHolder dh = getWorldDataByPlayerName(playerName); - if (dh != null) { - return dh.getPermissionsHandler(); - } - return null; - } - - private void verifyFirstRun() { - - /* - * Do not use the folder name if this - * is a Bukkit Forge server. - */ - if (plugin.getServer().getName().equalsIgnoreCase("BukkitForge")) { - serverDefaultWorldName = "overworld"; - - } else { - Properties server = new Properties(); - try { - server.load(new FileInputStream(new File("server.properties"))); - serverDefaultWorldName = server.getProperty("level-name").toLowerCase(); - } catch (IOException ex) { - GroupManager.logger.log(Level.SEVERE, null, ex); - } - } - setupWorldFolder(serverDefaultWorldName); - - } - - public void setupWorldFolder(String worldName) { - - String worldNameLowered = worldName.toLowerCase(); - + public void setupWorldFolder(final String worldName) { + final String worldNameLowered = worldName.toLowerCase(); worldsFolder = new File(plugin.getDataFolder(), "worlds"); if (!worldsFolder.exists()) { worldsFolder.mkdirs(); } - - File defaultWorldFolder = new File(worldsFolder, worldNameLowered); + final File defaultWorldFolder = new File(worldsFolder, worldNameLowered); if ((!defaultWorldFolder.exists()) && ((!mirrorsGroup.containsKey(worldNameLowered))) || (!mirrorsUser.containsKey(worldNameLowered))) { - /* * check and convert all old case sensitive folders to lower case */ - File casedWorldFolder = new File(worldsFolder, worldName); + final File casedWorldFolder = new File(worldsFolder, worldName); if ((casedWorldFolder.exists()) && (casedWorldFolder.getName().toLowerCase().equals(worldNameLowered))) { /* * Rename the old folder to the new lower cased format @@ -567,228 +556,137 @@ public class WorldsHolder { } if (defaultWorldFolder.exists()) { if (!mirrorsGroup.containsKey(worldNameLowered)) { - File groupsFile = new File(defaultWorldFolder, "groups.yml"); + final File groupsFile = new File(defaultWorldFolder, "groups.yml"); if (!groupsFile.exists() || groupsFile.length() == 0) { - - InputStream template = plugin.getResourceAsStream("groups.yml"); + final InputStream template = plugin.getResourceAsStream("groups.yml"); try { Tasks.copy(template, groupsFile); - } catch (IOException ex) { + } catch (final IOException ex) { GroupManager.logger.log(Level.SEVERE, null, ex); } } } - if (!mirrorsUser.containsKey(worldNameLowered)) { - File usersFile = new File(defaultWorldFolder, "users.yml"); + final File usersFile = new File(defaultWorldFolder, "users.yml"); if (!usersFile.exists() || usersFile.length() == 0) { - - InputStream template = plugin.getResourceAsStream("users.yml"); + final InputStream template = plugin.getResourceAsStream("users.yml"); try { Tasks.copy(template, usersFile); - } catch (IOException ex) { + } catch (final IOException ex) { GroupManager.logger.log(Level.SEVERE, null, ex); } - } } } } /** - * Copies the specified world data to another world - * - * @param fromWorld - * @param toWorld - * @return true if successfully copied. + * Backup the Groups/Users file + * + * @param w + * @param groups */ - public boolean cloneWorld(String fromWorld, String toWorld) { - - File fromWorldFolder = new File(worldsFolder, fromWorld.toLowerCase()); - File toWorldFolder = new File(worldsFolder, toWorld.toLowerCase()); - if (toWorldFolder.exists() || !fromWorldFolder.exists()) { - return false; - } - File fromWorldGroups = new File(fromWorldFolder, "groups.yml"); - File fromWorldUsers = new File(fromWorldFolder, "users.yml"); - if (!fromWorldGroups.exists() || !fromWorldUsers.exists()) { - return false; - } - File toWorldGroups = new File(toWorldFolder, "groups.yml"); - File toWorldUsers = new File(toWorldFolder, "users.yml"); - toWorldFolder.mkdirs(); + private void backupFile(final OverloadedWorldHolder w, final Boolean groups) { + final File backupFile = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + (groups ? "_g_" : "_u_") + Tasks.getDateString() + ".yml"); try { - Tasks.copy(fromWorldGroups, toWorldGroups); - Tasks.copy(fromWorldUsers, toWorldUsers); - } catch (IOException ex) { - Logger.getLogger(WorldsHolder.class.getName()).log(Level.SEVERE, null, ex); - return false; + Tasks.copy((groups ? w.getGroupsFile() : w.getUsersFile()), backupFile); + } catch (final IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); } - return true; } /** - * Wrapper for LoadWorld(String,Boolean) for backwards compatibility - * - * Load a world from file. - * If it already been loaded, summon reload method from dataHolder. - * + * Get the requested world data and update it's dataSource to be relevant + * for this world + * * @param worldName + * @return updated world holder */ - public void loadWorld(String worldName) { - - loadWorld(worldName, false); - } - - /** - * Load a world from file. - * If it already been loaded, summon reload method from dataHolder. - * - * @param worldName - */ - public void loadWorld(String worldName, Boolean isMirror) { - - String worldNameLowered = worldName.toLowerCase(); - + private OverloadedWorldHolder getUpdatedWorldData(final String worldName) { + final String worldNameLowered = worldName.toLowerCase(); if (worldsData.containsKey(worldNameLowered)) { - worldsData.get(worldNameLowered).reload(); - return; + final OverloadedWorldHolder data = worldsData.get(worldNameLowered); + data.updateDataSource(); + return data; } - GroupManager.logger.finest("Trying to load world " + worldName + "..."); - File thisWorldFolder = new File(worldsFolder, worldNameLowered); - if ((isMirror) || (thisWorldFolder.exists() && thisWorldFolder.isDirectory())) { + return null; + } - // Setup file handles, if not mirrored - File groupsFile = (mirrorsGroup.containsKey(worldNameLowered)) ? null : new File(thisWorldFolder, "groups.yml"); - File usersFile = (mirrorsUser.containsKey(worldNameLowered)) ? null : new File(thisWorldFolder, "users.yml"); + private void initialLoad() { + // load the initial world + initialWorldLoading(); + // Configure and load any mirrors and additional worlds as defined in config.yml + mirrorSetUp(); + // search the worlds folder for any manually created worlds (not listed in config.yml) + loadAllSearchedWorlds(); + } - if ((groupsFile != null) && (!groupsFile.exists())) { - throw new IllegalArgumentException("Groups file for world '" + worldName + "' doesnt exist: " + groupsFile.getPath()); + private void initialWorldLoading() { + // Load the default world + loadWorld(serverDefaultWorldName); + // defaultWorld = getUpdatedWorldData(serverDefaultWorldName); + } + + private void loadAllSearchedWorlds() { + /* + * Read all known worlds from Bukkit Create the data files if they don't + * already exist, and they are not mirrored. + */ + for (final World world : plugin.getServer().getWorlds()) { + GroupManager.logger.log(Level.FINE, "检查世界 " + world.getName() + " 的数据."); + if ((!worldsData.containsKey(world.getName().toLowerCase())) && ((!mirrorsGroup.containsKey(world.getName().toLowerCase())) || (!mirrorsUser.containsKey(world.getName().toLowerCase())))) { + if (worldsData.containsKey("all_unnamed_worlds")) { + final String usersMirror = mirrorsUser.get("all_unnamed_worlds"); + final String groupsMirror = mirrorsGroup.get("all_unnamed_worlds"); + if (usersMirror != null) + mirrorsUser.put(world.getName().toLowerCase(), usersMirror); + if (groupsMirror != null) + mirrorsGroup.put(world.getName().toLowerCase(), groupsMirror); + } + GroupManager.logger.log(Level.FINE, "创建世界 " + world.getName() + " 的数据."); + setupWorldFolder(world.getName()); } - if ((usersFile != null) && (!usersFile.exists())) { - throw new IllegalArgumentException("Users file for world '" + worldName + "' doesnt exist: " + usersFile.getPath()); - } - - WorldDataHolder tempHolder = new WorldDataHolder(worldNameLowered); - - // Map the group object for any mirror - if (mirrorsGroup.containsKey(worldNameLowered)) - tempHolder.setGroupsObject(this.getWorldData(mirrorsGroup.get(worldNameLowered)).getGroupsObject()); - else - tempHolder.loadGroups(groupsFile); - - // Map the user object for any mirror - if (mirrorsUser.containsKey(worldNameLowered)) - tempHolder.setUsersObject(this.getWorldData(mirrorsUser.get(worldNameLowered)).getUsersObject()); - else - tempHolder.loadUsers(usersFile); - - OverloadedWorldHolder thisWorldData = new OverloadedWorldHolder(tempHolder); - - // null the object so we don't keep file handles open where we shouldn't - tempHolder = null; - - // Set the file TimeStamps as it will be default from the initial load. - thisWorldData.setTimeStamps(); - - if (thisWorldData != null) { - GroupManager.logger.finest("Successful load of world " + worldName + "..."); - worldsData.put(worldNameLowered, thisWorldData); - return; - } - - // GroupManager.logger.severe("Failed to load world " + worldName + "..."); } - } - - /** - * Tells if the such world has been mapped. - * - * It will return true if world is a mirror. - * - * @param worldName - * @return true if world is loaded or mirrored. false if not listed - */ - public boolean isInList(String worldName) { - - if (worldsData.containsKey(worldName.toLowerCase()) || mirrorsGroup.containsKey(worldName.toLowerCase()) || mirrorsUser.containsKey(worldName.toLowerCase())) { - return true; - } - return false; - } - - /** - * Verify if world has it's own file permissions. - * - * @param worldName - * @return true if it has its own holder. false if not. - */ - public boolean hasOwnData(String worldName) { - - if (worldsData.containsKey(worldName.toLowerCase()) && (!mirrorsGroup.containsKey(worldName.toLowerCase()) || !mirrorsUser.containsKey(worldName.toLowerCase()))) { - return true; - } - return false; - } - - /** - * @return the defaultWorld - */ - public OverloadedWorldHolder getDefaultWorld() { - - return getUpdatedWorldData(serverDefaultWorldName); - } - - /** - * Returns all physically loaded worlds which have at least one of their own - * data sets for users or groups which isn't an identical mirror. - * - * @return ArrayList of all loaded worlds - */ - public ArrayList allWorldsDataList() { - - ArrayList list = new ArrayList(); - - for (String world : worldsData.keySet()) { - - if (!world.equalsIgnoreCase("all_unnamed_worlds")) { - - // Fetch the relevant world object - OverloadedWorldHolder data = getWorldData(world); - - if (!list.contains(data)) { - - String worldNameLowered = data.getName().toLowerCase(); - String usersMirror = mirrorsUser.get(worldNameLowered); - String groupsMirror = mirrorsGroup.get(worldNameLowered); - - // is users mirrored? - if (usersMirror != null) { - - // If both are mirrored - if (groupsMirror != null) { - - // if the data sources are the same, return the parent - if (usersMirror == groupsMirror) { - data = getWorldData(usersMirror.toLowerCase()); - - // Only add the parent if it's not already listed. - if (!list.contains(data)) - list.add(data); - - continue; - } - // Both data sources are mirrors, but they are from different parents - // so fall through to add the actual data object. - } - // Groups isn't a mirror so fall through to add this this worlds data source - } - - // users isn't mirrored so we need to add this worlds data source - list.add(data); + /* + * Loop over all folders within the worlds folder and attempt to load + * the world data + */ + for (final File folder : worldsFolder.listFiles()) { + if (folder.isDirectory() && !folder.getName().startsWith(".")) { + GroupManager.logger.info("载入世界数据: " + folder.getName()); + /* + * don't load any worlds which are already loaded or fully + * mirrored worlds that don't need data. + */ + if (!worldsData.containsKey(folder.getName().toLowerCase()) && ((!mirrorsGroup.containsKey(folder.getName().toLowerCase())) || (!mirrorsUser.containsKey(folder.getName().toLowerCase())))) { + /* + * Call setupWorldFolder to check case sensitivity and + * convert to lower case, before we attempt to load this + * world. + */ + setupWorldFolder(folder.getName()); + loadWorld(folder.getName().toLowerCase()); } } } - return list; + } + + private void verifyFirstRun() { + /* + * Do not use the folder name if this + * is a Bukkit Forge server. + */ + if (plugin.getServer().getName().equalsIgnoreCase("BukkitForge")) { + serverDefaultWorldName = "overworld"; + } else { + final Properties server = new Properties(); + try { + server.load(new FileInputStream(new File("server.properties"))); + serverDefaultWorldName = server.getProperty("level-name").toLowerCase(); + } catch (final IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + setupWorldFolder(serverDefaultWorldName); } } diff --git a/src/main/java/org/anjocaido/groupmanager/events/GMGroupEvent.java b/src/main/java/org/anjocaido/groupmanager/events/GMGroupEvent.java index 1c2cbae..2cc165c 100644 --- a/src/main/java/org/anjocaido/groupmanager/events/GMGroupEvent.java +++ b/src/main/java/org/anjocaido/groupmanager/events/GMGroupEvent.java @@ -10,71 +10,51 @@ import org.bukkit.event.HandlerList; * */ public class GMGroupEvent extends Event { - - /** - * - */ private static final HandlerList handlers = new HandlerList(); - protected Group group; - protected String groupName; - ////////////////////////////// - protected Action action; public GMGroupEvent(final Group group, final Action action) { - super(); - this.group = group; this.action = action; this.groupName = group.getName(); } public GMGroupEvent(final String groupName, final Action action) { - super(); - this.groupName = groupName; this.action = action; } public static HandlerList getHandlerList() { - return handlers; } public Action getAction() { - return this.action; } public Group getGroup() { - return group; } public String getGroupName() { - return groupName; } @Override public HandlerList getHandlers() { - return handlers; } public void schedule(final GMGroupEvent event) { - synchronized (GroupManager.getGMEventHandler().getServer()) { if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { - @Override public void run() { - GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); } }, 1) == -1) diff --git a/src/main/java/org/anjocaido/groupmanager/events/GMSystemEvent.java b/src/main/java/org/anjocaido/groupmanager/events/GMSystemEvent.java index 84c2fc0..a775674 100644 --- a/src/main/java/org/anjocaido/groupmanager/events/GMSystemEvent.java +++ b/src/main/java/org/anjocaido/groupmanager/events/GMSystemEvent.java @@ -6,61 +6,47 @@ import org.bukkit.event.HandlerList; /** * @author ElgarL - * + * */ public class GMSystemEvent extends Event { - - /** - * - */ private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - - return handlers; - } - - public static HandlerList getHandlerList() { - - return handlers; - } - - ////////////////////////////// - protected Action action; - public GMSystemEvent(Action action) { - + public GMSystemEvent(final Action action) { super(); - this.action = action; } - public Action getAction() { + ////////////////////////////// + public static HandlerList getHandlerList() { + return handlers; + } + public Action getAction() { return this.action; } + @Override + public HandlerList getHandlers() { + return handlers; + } + + public void schedule(final GMSystemEvent event) { + synchronized (GroupManager.getGMEventHandler().getServer()) { + if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { + @Override + public void run() { + GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); + } + }, 1) == -1) + GroupManager.logger.warning("Could not schedule GM Event."); + } + } + public enum Action { RELOADED, SAVED, DEFAULT_GROUP_CHANGED, VALIDATE_TOGGLE, } - - public void schedule(final GMSystemEvent event) { - - synchronized (GroupManager.getGMEventHandler().getServer()) { - if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { - - @Override - public void run() { - - GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); - } - }, 1) == -1) - GroupManager.logger.warning("Could not schedule GM Event."); - } - } } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/events/GMUserEvent.java b/src/main/java/org/anjocaido/groupmanager/events/GMUserEvent.java index 02f323c..6d9d492 100644 --- a/src/main/java/org/anjocaido/groupmanager/events/GMUserEvent.java +++ b/src/main/java/org/anjocaido/groupmanager/events/GMUserEvent.java @@ -7,66 +7,62 @@ import org.bukkit.event.HandlerList; /** * @author ElgarL - * + * */ public class GMUserEvent extends Event { - /** - * - */ private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - - return handlers; - } - - public static HandlerList getHandlerList() { - - return handlers; - } - - ////////////////////////////// - protected User user; - protected String userName; - + ////////////////////////////// protected Action action; - public GMUserEvent(User user, Action action) { - + public GMUserEvent(final String userName, final Action action) { super(); + this.userName = userName; + this.action = action; + } + public GMUserEvent(final User user, final Action action) { + super(); this.user = user; this.action = action; this.userName = user.getLastName(); } - public GMUserEvent(String userName, Action action) { - - super(); - - this.userName = userName; - this.action = action; + public static HandlerList getHandlerList() { + return handlers; } public Action getAction() { - return this.action; } - public User getUser() { + @Override + public HandlerList getHandlers() { + return handlers; + } + public User getUser() { return user; } public String getUserName() { - return userName; } + public void schedule(final GMUserEvent event) { + synchronized (GroupManager.getGMEventHandler().getServer()) { + if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { + @Override + public void run() { + GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); + } + }, 1) == -1) + GroupManager.logger.warning("Could not schedule GM Event."); + } + } + public enum Action { USER_PERMISSIONS_CHANGED, USER_INHERITANCE_CHANGED, @@ -76,19 +72,4 @@ public class GMUserEvent extends Event { USER_ADDED, USER_REMOVED, } - - public void schedule(final GMUserEvent event) { - - synchronized (GroupManager.getGMEventHandler().getServer()) { - if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { - - @Override - public void run() { - - GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); - } - }, 1) == -1) - GroupManager.logger.warning("Could not schedule GM Event."); - } - } } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/events/GMWorldListener.java b/src/main/java/org/anjocaido/groupmanager/events/GMWorldListener.java index 5199cdc..ddc2028 100644 --- a/src/main/java/org/anjocaido/groupmanager/events/GMWorldListener.java +++ b/src/main/java/org/anjocaido/groupmanager/events/GMWorldListener.java @@ -8,54 +8,43 @@ import org.bukkit.event.world.WorldInitEvent; /** * @author ElgarL - * + * * Handle new world creation from other plugins - * + * */ public class GMWorldListener implements Listener { private final GroupManager plugin; - public GMWorldListener(GroupManager instance) { - + public GMWorldListener(final GroupManager instance) { plugin = instance; registerEvents(); } - private void registerEvents() { - - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - @EventHandler(priority = EventPriority.LOWEST) - public void onWorldInit(WorldInitEvent event) { - - String worldName = event.getWorld().getName(); - + public void onWorldInit(final WorldInitEvent event) { + final String worldName = event.getWorld().getName(); if (GroupManager.isLoaded() && !plugin.getWorldsHolder().isInList(worldName)) { - GroupManager.logger.info("New world detected..."); - GroupManager.logger.info("Creating data for: " + worldName); - + GroupManager.logger.info("发现一个新的世界..."); + GroupManager.logger.info("创建新的数据: " + worldName); if (plugin.getWorldsHolder().isWorldKnown("all_unnamed_worlds")) { - - String usersMirror = plugin.getWorldsHolder().getMirrorsUser().get("all_unnamed_worlds"); - String groupsMirror = plugin.getWorldsHolder().getMirrorsGroup().get("all_unnamed_worlds"); - + final String usersMirror = plugin.getWorldsHolder().getMirrorsUser().get("all_unnamed_worlds"); + final String groupsMirror = plugin.getWorldsHolder().getMirrorsGroup().get("all_unnamed_worlds"); if (usersMirror != null) plugin.getWorldsHolder().getMirrorsUser().put(worldName.toLowerCase(), usersMirror); - if (groupsMirror != null) plugin.getWorldsHolder().getMirrorsGroup().put(worldName.toLowerCase(), groupsMirror); - } - plugin.getWorldsHolder().setupWorldFolder(worldName); plugin.getWorldsHolder().loadWorld(worldName); - if (plugin.getWorldsHolder().isInList(worldName)) { - GroupManager.logger.info("Don't forget to configure/mirror this world in config.yml."); + GroupManager.logger.info("请不要忘记配置或者镜像这个世界在 config.yml."); } else - GroupManager.logger.severe("Failed to configure this world."); + GroupManager.logger.severe("自动配置失败 请联系开发者."); } } + + private void registerEvents() { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/events/GroupManagerEventHandler.java b/src/main/java/org/anjocaido/groupmanager/events/GroupManagerEventHandler.java index 20845af..6691ef0 100644 --- a/src/main/java/org/anjocaido/groupmanager/events/GroupManagerEventHandler.java +++ b/src/main/java/org/anjocaido/groupmanager/events/GroupManagerEventHandler.java @@ -7,67 +7,46 @@ import org.bukkit.Server; /** * @author ElgarL - * + * * Handles all Event generation. - * + * */ public class GroupManagerEventHandler { private final Server server; private final GroupManager plugin; - public GroupManagerEventHandler(GroupManager plugin) { + public GroupManagerEventHandler(final GroupManager plugin) { this.plugin = plugin; this.server = plugin.getServer(); } - protected void callEvent(GMGroupEvent event) { - - event.schedule(event); + public void callEvent(final GMSystemEvent.Action action) { + callEvent(new GMSystemEvent(action)); } - protected void callEvent(GMUserEvent event) { - - event.schedule(event); - } - - protected void callEvent(GMSystemEvent event) { - - event.schedule(event); - } - - public void callEvent(Group group, GMGroupEvent.Action action) { - + public void callEvent(final Group group, final GMGroupEvent.Action action) { callEvent(new GMGroupEvent(group, action)); } - public void callEvent(String groupName, GMGroupEvent.Action action) { - + public void callEvent(final String groupName, final GMGroupEvent.Action action) { callEvent(new GMGroupEvent(groupName, action)); } - public void callEvent(User user, GMUserEvent.Action action) { - - callEvent(new GMUserEvent(user, action)); - } - - public void callEvent(String userName, GMUserEvent.Action action) { - + public void callEvent(final String userName, final GMUserEvent.Action action) { callEvent(new GMUserEvent(userName, action)); } - public void callEvent(GMSystemEvent.Action action) { - - callEvent(new GMSystemEvent(action)); + public void callEvent(final User user, final GMUserEvent.Action action) { + callEvent(new GMUserEvent(user, action)); } /** * @return the plugin */ public GroupManager getPlugin() { - return plugin; } @@ -75,8 +54,19 @@ public class GroupManagerEventHandler { * @return the server */ public Server getServer() { - return server; } + protected void callEvent(final GMGroupEvent event) { + event.schedule(event); + } + + protected void callEvent(final GMSystemEvent event) { + event.schedule(event); + } + + protected void callEvent(final GMUserEvent event) { + event.schedule(event); + } + } \ No newline at end of file diff --git a/src/main/java/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java b/src/main/java/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java index 35eef5e..a6a19bc 100644 --- a/src/main/java/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java +++ b/src/main/java/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java @@ -31,7 +31,6 @@ import org.bukkit.entity.Player; * @author gabrielcouto, ElgarL */ public class AnjoPermissionsHandler extends PermissionsReaderInterface { - WorldDataHolder ph = null; /** @@ -40,19 +39,16 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @param holder */ public AnjoPermissionsHandler(final WorldDataHolder holder) { - ph = holder; } @Override public void addGroupInfo(final String name, final String path, final Object data) { - ph.getGroup(name).getVariables().addVar(path, data); } @Override public void addUserInfo(final String name, final String path, final Object data) { - ph.getUser(name).getVariables().addVar(path, data); } @@ -65,7 +61,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean canGroupBuild(final String groupName) { - final Group g = ph.getGroup(groupName); if (g == null) { return false; @@ -81,9 +76,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return true if the user can build */ public boolean canUserBuild(final String userName) { - return getPermissionBoolean(userName, "build"); - } /** @@ -99,7 +92,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult */ public PermissionCheckResult checkFullGMPermission(final User user, final String targetPermission, final Boolean checkBukkit) { - /* * Report no permissions under the following conditions. * @@ -108,14 +100,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ if (user == null || targetPermission == null || targetPermission.isEmpty() || (!Bukkit.getServer().getOnlineMode() && (checkPermission(user, "groupmanager.noofflineperms", false).resultType == PermissionCheckResult.Type.FOUND))) { - final PermissionCheckResult result = new PermissionCheckResult(); result.accessLevel = targetPermission; result.resultType = PermissionCheckResult.Type.NOTFOUND; - return result; } - return checkPermission(user, targetPermission, checkBukkit); } @@ -128,7 +117,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult */ public PermissionCheckResult checkFullUserPermission(final User user, final String targetPermission) { - return checkFullGMPermission(user, targetPermission, true); } @@ -141,7 +129,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return the node if permission is found. if not found, return null */ public PermissionCheckResult checkGroupOnlyPermission(final Group group, final String permission) { - group.sortPermissions(); final PermissionCheckResult result = new PermissionCheckResult(); result.owner = group; @@ -172,38 +159,29 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult */ public PermissionCheckResult checkGroupPermissionWithInheritance(final Group start, final String targetPermission) { - if (start == null || targetPermission == null) { return null; } - final LinkedList stack = new LinkedList(); final List alreadyVisited = new ArrayList(); PermissionCheckResult result = new PermissionCheckResult(); - stack.push(start); alreadyVisited.add(start); - // Set defaults. result.askedPermission = targetPermission; result.resultType = PermissionCheckResult.Type.NOTFOUND; - while (!stack.isEmpty()) { final Group now = stack.pop(); final PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission); - if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { - if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { resultNow.accessLevel = targetPermission; return resultNow; } - // Negation found so store for later // as we need to continue looking for an Exception. result = resultNow; } - for (final String sonName : now.getInherits()) { final Group son = ph.getGroup(sonName); if (son != null && !alreadyVisited.contains(son)) { @@ -213,7 +191,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { } } } - return result; } @@ -225,7 +202,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult */ public PermissionCheckResult checkUserOnlyPermission(final User user, final String permission) { - user.sortPermissions(); final PermissionCheckResult result = new PermissionCheckResult(); result.askedPermission = permission; @@ -249,12 +225,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return true if permission was found. false if not, or was negated. */ public boolean checkUserPermission(final User user, final String permission) { - final PermissionCheckResult result = checkFullGMPermission(user, permission, true); if (result.resultType == PermissionCheckResult.Type.EXCEPTION || result.resultType == PermissionCheckResult.Type.FOUND) { return true; } - return false; } @@ -277,12 +251,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult.Type */ public PermissionCheckResult.Type comparePermissionString(final String userAccessLevel, final String fullPermissionName) { - int userAccessLevelLength; if (userAccessLevel == null || fullPermissionName == null || fullPermissionName.length() == 0 || (userAccessLevelLength = userAccessLevel.length()) == 0) { return PermissionCheckResult.Type.NOTFOUND; } - PermissionCheckResult.Type result = PermissionCheckResult.Type.FOUND; int userAccessLevelOffset = 0; if (userAccessLevel.charAt(0) == '+') { @@ -292,15 +264,12 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { userAccessLevelOffset = 1; result = PermissionCheckResult.Type.NEGATION; } - if (fullPermissionName.equals(userAccessLevel)) { return result; } - if ("groupmanager.noofflineperms".equals(fullPermissionName)) { result = PermissionCheckResult.Type.NOTFOUND; } - if ("*".regionMatches(0, userAccessLevel, userAccessLevelOffset, userAccessLevelLength - userAccessLevelOffset)) { return result; } @@ -310,7 +279,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { } else { fullPermissionNameOffset = 0; } - if (userAccessLevel.charAt(userAccessLevel.length() - 1) == '*') { return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, userAccessLevelLength - userAccessLevelOffset - 1) ? result : PermissionCheckResult.Type.NOTFOUND; } @@ -330,11 +298,8 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public List getAllPlayersPermissions(final String userName) { - final List perms = new ArrayList(); - perms.addAll(getAllPlayersPermissions(userName, true)); - return perms; } @@ -347,77 +312,55 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public Set getAllPlayersPermissions(final String userName, final Boolean includeChildren) { - final Set playerPermArray = new LinkedHashSet(); final Set overrides = new LinkedHashSet(); - // Add the players own permissions. playerPermArray.addAll(populatePerms(ph.getUser(userName).getPermissionList(), includeChildren)); - final ArrayList alreadyProcessed = new ArrayList(); - // fetch all group permissions for (final String group : getGroups(userName)) { // Don't process a group more than once. if (!alreadyProcessed.contains(group)) { alreadyProcessed.add(group); - Set groupPermArray = new LinkedHashSet(); - if (group.startsWith("g:") && GroupManager.getGlobalGroups().hasGroup(group)) { // GlobalGroups groupPermArray = populatePerms(GroupManager.getGlobalGroups().getGroupsPermissions(group), includeChildren); - } else { // World Groups groupPermArray = populatePerms(ph.getGroup(group).getPermissionList(), includeChildren); } - // Add all group permissions, unless negated by earlier permissions. for (final String perm : groupPermArray) { final boolean negated = (perm.startsWith("-")); - // Overridden (Exception) permission defeats negation. if (perm.startsWith("+")) { overrides.add(perm.substring(1)); continue; } - // Perm doesn't already exists and there is no negation for it // or It's a negated perm where a normal perm doesn't exists (don't allow inheritance to negate higher perms) if ((!negated && !playerPermArray.contains(perm) && !wildcardNegation(playerPermArray, perm)) || (negated && !playerPermArray.contains(perm.substring(1)) && !wildcardNegation(playerPermArray, perm.substring(1)))) playerPermArray.add(perm); - } } - } - // Process overridden permissions - final Iterator itr = overrides.iterator(); - while (itr.hasNext()) { - final String node = itr.next(); - if (playerPermArray.contains("-" + node)) { playerPermArray.remove("-" + node); } - playerPermArray.add(node); - } - // Collections.sort(playerPermArray, StringPermissionComparator.getInstance()); - return playerPermArray; } @Override public Group getDefaultGroup() { - return ph.getDefaultGroup(); } @@ -429,7 +372,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getGroup(final String userName) { - return ph.getUser(userName).getGroup().getName(); } @@ -443,7 +385,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean getGroupPermissionBoolean(final String group, final String variable) { - final Group start = ph.getGroup(group); if (start == null) { return false; @@ -465,7 +406,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public double getGroupPermissionDouble(final String group, final String variable) { - final Group start = ph.getGroup(group); if (start == null) { return -1; @@ -487,7 +427,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public int getGroupPermissionInteger(final String groupName, final String variable) { - final Group start = ph.getGroup(groupName); if (start == null) { return -1; @@ -509,7 +448,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getGroupPermissionString(final String groupName, final String variable) { - final Group start = ph.getGroup(groupName); if (start == null) { return null; @@ -529,7 +467,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getGroupPrefix(final String groupName) { - final Group g = ph.getGroup(groupName); if (g == null) { return ""; @@ -547,12 +484,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String[] getGroups(final String userName) { - final ArrayList allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup()); for (final Group subg : ph.getUser(userName).subGroupListCopy()) { allGroups.addAll(listAllGroupsInherited(subg)); } - final String[] arr = new String[allGroups.size()]; return allGroups.toArray(arr); } @@ -565,7 +500,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getGroupSuffix(final String groupName) { - final Group g = ph.getGroup(groupName); if (g == null) { return ""; @@ -603,12 +537,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { return -1; } return data.getVariables().getVarDouble(path); - } @Override public int getInfoInteger(final String entryName, final String path, final boolean isGroup) { - if (isGroup) { final Group data = ph.getGroup(entryName); if (data == null) { @@ -625,7 +557,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { @Override public String getInfoString(final String entryName, final String path, final boolean isGroup) { - if (isGroup) { final Group data = ph.getGroup(entryName); if (data == null) { @@ -651,7 +582,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean getPermissionBoolean(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return false; @@ -691,7 +621,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public double getPermissionDouble(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return -1.0D; @@ -731,7 +660,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public int getPermissionInteger(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return -1; @@ -771,7 +699,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getPermissionString(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return ""; @@ -810,9 +737,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return Name of player's primary group */ public String getPrimaryGroup(final String user) { - return getGroup(user); - } /** @@ -824,7 +749,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean getUserPermissionBoolean(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return false; @@ -841,7 +765,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public double getUserPermissionDouble(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return -1; @@ -858,7 +781,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public int getUserPermissionInteger(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return -1; @@ -875,7 +797,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getUserPermissionString(final String user, final String variable) { - final User auser = ph.getUser(user); if (auser == null) { return ""; @@ -895,12 +816,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getUserPrefix(final String user) { - final String prefix = ph.getUser(user).getVariables().getVarString("prefix"); if (prefix.length() != 0) { return prefix; } - return getGroupPrefix(getGroup(user)); } @@ -916,14 +835,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public String getUserSuffix(final String user) { - final String suffix = ph.getUser(user).getVariables().getVarString("suffix"); if (suffix.length() != 0) { return suffix; } - return getGroupSuffix(getGroup(user)); - } /** @@ -935,7 +851,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean has(final Player player, final String permission) { - return permission(player, permission); } @@ -951,7 +866,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return true if it inherits the group. */ public boolean hasGroupInInheritance(final Group start, final String askedGroup) { - if (start == null || askedGroup == null) { return false; } @@ -992,7 +906,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean inGroup(final String name, final String group) { - if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) { return true; } @@ -1014,7 +927,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return the group that passed on test. null if no group passed. */ public ArrayList listAllGroupsInherited(final Group start) { - if (start == null) { return null; } @@ -1048,7 +960,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return The group if found. Null if not. */ public Group nextGroupWithVariable(final Group start, final String targetVariable) { - if (start == null || targetVariable == null) { return null; } @@ -1081,7 +992,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @Override public boolean permission(final Player player, final String permission) { - return checkUserPermission(ph.getUser(player.getName()).updatePlayer(player), permission); } @@ -1093,19 +1003,16 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return true if the player has the permission */ public boolean permission(final String playerName, final String permission) { - return checkUserPermission(ph.getUser(playerName), permission); } @Override public void removeGroupInfo(final String name, final String path) { - ph.getGroup(name).getVariables().removeVar(path); } @Override public void removeUserInfo(final String name, final String path) { - ph.getUser(name).getVariables().removeVar(path); } @@ -1121,7 +1028,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { */ @SuppressWarnings("unused") private Group breadthFirstSearch(final Group start, final String targerPermission) { - if (start == null || targerPermission == null) { return null; } @@ -1160,11 +1066,9 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return PermissionCheckResult */ private PermissionCheckResult checkPermission(final User user, final String targetPermission, final Boolean checkBukkit) { - PermissionCheckResult result = new PermissionCheckResult(); result.accessLevel = targetPermission; result.resultType = PermissionCheckResult.Type.NOTFOUND; - if (checkBukkit) { // Check Bukkit perms to support plugins which add perms via code // (Heroes). @@ -1176,78 +1080,54 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { return result; } } - final PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission); if (resultUser.resultType != PermissionCheckResult.Type.NOTFOUND) { - resultUser.accessLevel = targetPermission; - if (resultUser.resultType == PermissionCheckResult.Type.EXCEPTION) { return resultUser; } - result = resultUser; - } - // IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT AN EXCEPTION final PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission); if (resultGroup.resultType != PermissionCheckResult.Type.NOTFOUND) { - resultGroup.accessLevel = targetPermission; - if (resultGroup.resultType == PermissionCheckResult.Type.EXCEPTION) { return resultGroup; } - // Do not override higher level permissions with negations. if (result.resultType == PermissionCheckResult.Type.NOTFOUND) { result = resultGroup; } - } - // Do we have a high level negation? final boolean negated = (result.resultType == PermissionCheckResult.Type.NEGATION); - // SUBGROUPS CHECK for (final Group subGroup : user.subGroupListCopy()) { - final PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission); if (resultSubGroup.resultType != PermissionCheckResult.Type.NOTFOUND) { - resultSubGroup.accessLevel = targetPermission; - // Allow exceptions to override higher level negations // but low level negations can not remove higher level permissions. if (resultSubGroup.resultType == PermissionCheckResult.Type.EXCEPTION) { - return resultSubGroup; - } else if ((resultSubGroup.resultType == PermissionCheckResult.Type.FOUND) && (result.resultType != PermissionCheckResult.Type.NEGATION) && !negated) { - result = resultSubGroup; - } else if ((resultSubGroup.resultType == PermissionCheckResult.Type.NEGATION) && !negated) { - result = resultSubGroup; } - } } - // THEN IT RETURNS A NOT FOUND // OR THE RESULT OF THE SUBGROUP SEARCH. return result; } private Set populatePerms(final List permsList, final boolean includeChildren) { - // Create a new array so it's modifiable. final List perms = new ArrayList(permsList); final Set permArray = new LinkedHashSet(); Boolean allPerms = false; - // Allow * node to populate ALL permissions to Bukkit. if (perms.contains("*")) { permArray.addAll(GroupManager.BukkitPermissions.getAllRegisteredPermissions(includeChildren)); @@ -1256,7 +1136,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { // Remove the no offline perms node as this should not be given. perms.remove("groupmanager.noofflineperms"); } - for (final String perm : perms) { /** * all permission sets are passed here pre-sorted, alphabetically. @@ -1264,13 +1143,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * other than *. */ final boolean negated = perm.startsWith("-"); - if (!permArray.contains(perm)) { permArray.add(perm); - if ((negated) && (permArray.contains(perm.substring(1)))) permArray.remove(perm.substring(1)); - /** * Process child nodes if required, * or this is a negated node AND we used * to include all @@ -1278,21 +1154,16 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * in which case we need to remove all children of that node. */ if ((includeChildren) || (negated && allPerms)) { - final Map children = GroupManager.BukkitPermissions.getAllChildren((negated ? perm.substring(1) : perm), new LinkedHashSet()); - if (children != null) { if (negated) if (allPerms) { - // Remove children of negated nodes for (final String child : children.keySet()) if (children.get(child)) if (permArray.contains(child)) permArray.remove(child); - } else { - // Add child nodes for (final String child : children.keySet()) if (children.get(child)) @@ -1303,7 +1174,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { } } } - return permArray; } @@ -1315,14 +1185,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { * @return */ private boolean wildcardNegation(final Set playerPermArray, final String node) { - /* * Check for a negated parent with a wildcard or negated permission */ - if (playerPermArray.contains("-" + node)) return true; - final String[] parts = node.split("\\."); final StringBuilder builder = new StringBuilder(node.length()); for (final String part : parts) { @@ -1331,16 +1198,13 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface { GroupManager.logger.fine("Wildcard Negation found for " + node); return true; } - builder.deleteCharAt(builder.length() - 1); builder.append(part).append('.'); } - /* * No negated parent found so return false. */ GroupManager.logger.fine("No Negation found for " + node); return false; - } } diff --git a/src/main/java/org/anjocaido/groupmanager/permissions/BukkitPermissions.java b/src/main/java/org/anjocaido/groupmanager/permissions/BukkitPermissions.java index 11eec19..c28c600 100644 --- a/src/main/java/org/anjocaido/groupmanager/permissions/BukkitPermissions.java +++ b/src/main/java/org/anjocaido/groupmanager/permissions/BukkitPermissions.java @@ -14,7 +14,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ - package org.anjocaido.groupmanager.permissions; import java.lang.reflect.Field; @@ -71,28 +70,21 @@ public class BukkitPermissions { protected LinkedHashMap registeredPermissions = new LinkedHashMap(); protected GroupManager plugin; protected boolean dumpAllPermissions = true; - protected boolean dumpMatchedPermissions = true; - private boolean player_join = false; public BukkitPermissions(final GroupManager plugin) { - this.plugin = plugin; this.reset(); this.registerEvents(); - - GroupManager.logger.info("Superperms support enabled."); + GroupManager.logger.info("启用 Bukkit Permissions 支持."); } public void collectPermissions() { - registeredPermissions.clear(); - for (final Permission perm : Bukkit.getPluginManager().getPermissions()) { registeredPermissions.put(perm.getName().toLowerCase(), perm); } - } /** @@ -106,17 +98,13 @@ public class BukkitPermissions { * @return Map of child permissions */ public Map getAllChildren(final String node, final Set playerPermArray) { - final LinkedList stack = new LinkedList(); final Map alreadyVisited = new HashMap(); stack.push(node); alreadyVisited.put(node, true); - while (!stack.isEmpty()) { final String now = stack.pop(); - final Map children = getChildren(now); - if ((children != null) && (!playerPermArray.contains("-" + now))) { for (final String childName : children.keySet()) { if (!alreadyVisited.containsKey(childName)) { @@ -129,7 +117,6 @@ public class BukkitPermissions { alreadyVisited.remove(node); if (!alreadyVisited.isEmpty()) return alreadyVisited; - return null; } @@ -141,13 +128,10 @@ public class BukkitPermissions { * @return List of all permission nodes */ public List getAllRegisteredPermissions(final boolean includeChildren) { - final List perms = new ArrayList(); - for (final String key : registeredPermissions.keySet()) { if (!perms.contains(key)) { perms.add(key); - if (includeChildren) { final Map children = getAllChildren(key, new HashSet()); if (children != null) { @@ -157,7 +141,6 @@ public class BukkitPermissions { } } } - } return perms; } @@ -171,20 +154,16 @@ public class BukkitPermissions { * @return Map of child permissions */ public Map getChildren(final String node) { - final Permission perm = registeredPermissions.get(node.toLowerCase()); if (perm == null) return null; - return perm.getChildren(); - } /** * @return the player_join */ public boolean isPlayer_join() { - return player_join; } @@ -195,9 +174,7 @@ public class BukkitPermissions { * @return List of permissions */ public List listPerms(final Player player) { - final List perms = new ArrayList(); - /* * // All permissions registered with Bukkit for this player * PermissionAttachment attachment = this.attachments.get(player); @@ -207,7 +184,6 @@ public class BukkitPermissions { * attachment.getPermissions().entrySet()){ perms.add(" " + * entry.getKey() + " = " + entry.getValue()); } */ - perms.add("Effective Permissions:"); for (final PermissionAttachmentInfo info : player.getEffectivePermissions()) { if (info.getValue() == true) @@ -220,7 +196,6 @@ public class BukkitPermissions { * Remove all attachments in case of a restart or reload. */ public void removeAllAttachments() { - /* * Remove all attachments. */ @@ -231,7 +206,6 @@ public class BukkitPermissions { } public void reset() { - /* * collect new permissions * and register all attachments. @@ -245,7 +219,6 @@ public class BukkitPermissions { * the player_join to set */ public void setPlayer_join(final boolean player_join) { - this.player_join = player_join; } @@ -253,14 +226,12 @@ public class BukkitPermissions { * force Bukkit to update every OnlinePlayers permissions. */ public void updateAllPlayers() { - for (final Player player : Bukkit.getServer().getOnlinePlayers()) { updatePermissions(player); } } public void updatePermissions(final Player player) { - this.updatePermissions(player, null); } @@ -272,20 +243,15 @@ public class BukkitPermissions { * @param world */ public void updatePermissions(final Player player, String world) { - if (player == null || !GroupManager.isLoaded()) { return; } - final String name = player.getName(); - // Reset the User objects player reference. final User user = plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(name); if (user != null) user.updatePlayer(player); - PermissionAttachment attachment; - // Find the players current attachment, or add a new one. if (this.attachments.containsKey(name)) { attachment = this.attachments.get(name); @@ -293,26 +259,21 @@ public class BukkitPermissions { attachment = player.addAttachment(plugin); this.attachments.put(name, attachment); } - if (world == null) { world = player.getWorld().getName(); } - // Add all permissions for this player (GM only) // child nodes will be calculated by Bukkit. List playerPermArray = new ArrayList(plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getAllPlayersPermissions(name, false)); final LinkedHashMap newPerms = new LinkedHashMap(); - // Sort the perm list by parent/child, so it will push to superperms // correctly. playerPermArray = sort(playerPermArray); - Boolean value = false; for (final String permission : playerPermArray) { value = (!permission.startsWith("-")); newPerms.put((value ? permission : permission.substring(1)), value); } - /* * Do not push any perms to bukkit if... * We are in offline mode @@ -322,14 +283,12 @@ public class BukkitPermissions { removeAttachment(name); return; } - /** * This is put in place until such a time as Bukkit pull 466 is * implemented https://github.com/Bukkit/Bukkit/pull/466 */ try { // Codename_B source synchronized (attachment.getPermissible()) { - @SuppressWarnings("unchecked") final Map orig = (Map) permissions.get(attachment); // Clear the map (faster than removing the attachment and @@ -339,14 +298,12 @@ public class BukkitPermissions { orig.putAll(newPerms); // That's all folks! attachment.getPermissible().recalculatePermissions(); - } } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } - GroupManager.logger.finest("Attachment updated for: " + name); } @@ -354,15 +311,12 @@ public class BukkitPermissions { * force Bukkit to update this Players permissions. */ public void updatePlayer(final Player player) { - if (player != null) this.updatePermissions(player, null); } private void registerEvents() { - final PluginManager manager = plugin.getServer().getPluginManager(); - manager.registerEvents(new PlayerEvents(), plugin); manager.registerEvents(new BukkitEvents(), plugin); } @@ -373,7 +327,6 @@ public class BukkitPermissions { * @param player */ private void removeAttachment(final String playerName) { - if (attachments.containsKey(playerName)) { attachments.get(playerName).remove(); attachments.remove(playerName); @@ -387,9 +340,7 @@ public class BukkitPermissions { * @return List sorted for priority */ private List sort(final List permList) { - final List result = new ArrayList(); - for (final String key : permList) { /* * Ignore stupid plugins which add empty permission nodes. @@ -398,13 +349,10 @@ public class BukkitPermissions { final String a = key.charAt(0) == '-' ? key.substring(1) : key; final Map allchildren = GroupManager.BukkitPermissions.getAllChildren(a, new HashSet()); if (allchildren != null) { - final ListIterator itr = result.listIterator(); - while (itr.hasNext()) { final String node = itr.next(); final String b = node.charAt(0) == '-' ? node.substring(1) : node; - // Insert the parent node before the child if (allchildren.containsKey(b)) { itr.set(key); @@ -417,25 +365,20 @@ public class BukkitPermissions { result.add(key); } } - return result; } protected class BukkitEvents implements Listener { - @EventHandler(priority = EventPriority.NORMAL) public void onPluginDisable(final PluginDisableEvent event) { - collectPermissions(); // updateAllPlayers(); } @EventHandler(priority = EventPriority.NORMAL) public void onPluginEnable(final PluginEnableEvent event) { - if (!GroupManager.isLoaded()) return; - collectPermissions(); updateAllPlayers(); } @@ -448,32 +391,24 @@ public class BukkitPermissions { * */ protected class PlayerEvents implements Listener { - @EventHandler(priority = EventPriority.LOWEST) public void onPlayerChangeWorld(final PlayerChangedWorldEvent event) { // has changed worlds - updatePermissions(event.getPlayer(), event.getPlayer().getWorld().getName()); } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerJoin(final PlayerJoinEvent event) { - setPlayer_join(true); final Player player = event.getPlayer(); - - GroupManager.logger.finest("Player Join event: " + player.getName()); - + GroupManager.logger.finest("玩家进入游戏: " + player.getName()); /* * Tidy up any lose ends */ removeAttachment(player.getName()); - // force GM to create the player if they are not already listed. plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(player.getUniqueId().toString(), player.getName()); - setPlayer_join(false); updatePermissions(event.getPlayer()); - setPlayer_join(false); } @@ -482,17 +417,13 @@ public class BukkitPermissions { */ @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerQuit(final PlayerQuitEvent event) { - if (!GroupManager.isLoaded()) return; - final Player player = event.getPlayer(); - /* * force remove any attachments as bukkit may not */ removeAttachment(player.getName()); } } - } diff --git a/src/main/java/org/anjocaido/groupmanager/utils/GMLoggerHandler.java b/src/main/java/org/anjocaido/groupmanager/utils/GMLoggerHandler.java index cefaa52..cca16dd 100644 --- a/src/main/java/org/anjocaido/groupmanager/utils/GMLoggerHandler.java +++ b/src/main/java/org/anjocaido/groupmanager/utils/GMLoggerHandler.java @@ -9,15 +9,14 @@ import java.util.logging.Level; import java.util.logging.LogRecord; /** - * + * * @author gabrielcouto */ public class GMLoggerHandler extends ConsoleHandler { @Override - public void publish(LogRecord record) { - - String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage(); + public void publish(final LogRecord record) { + final String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage(); if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) { System.err.println(message); } else { diff --git a/src/main/java/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java b/src/main/java/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java index ff98f25..f5b19c9 100644 --- a/src/main/java/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java +++ b/src/main/java/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java @@ -6,11 +6,10 @@ package org.anjocaido.groupmanager.utils; /** * Just a list of commands for this plugin - * + * * @author gabrielcouto */ public enum GroupManagerPermissions { - manuadd, manudel, manuaddsub, diff --git a/src/main/java/org/anjocaido/groupmanager/utils/StringPermissionComparator.java b/src/main/java/org/anjocaido/groupmanager/utils/StringPermissionComparator.java index 1fdaaee..19eda05 100644 --- a/src/main/java/org/anjocaido/groupmanager/utils/StringPermissionComparator.java +++ b/src/main/java/org/anjocaido/groupmanager/utils/StringPermissionComparator.java @@ -7,18 +7,27 @@ package org.anjocaido.groupmanager.utils; import java.util.Comparator; /** - * + * * @author gabrielcouto */ public class StringPermissionComparator implements Comparator { - @Override - public int compare(String permA, String permB) { + private static StringPermissionComparator instance; - boolean ap = permA.startsWith("+"); - boolean bp = permB.startsWith("+"); - boolean am = permA.startsWith("-"); - boolean bm = permB.startsWith("-"); + public static StringPermissionComparator getInstance() { + + if (instance == null) { + instance = new StringPermissionComparator(); + } + return instance; + } + + @Override + public int compare(final String permA, final String permB) { + final boolean ap = permA.startsWith("+"); + final boolean bp = permB.startsWith("+"); + final boolean am = permA.startsWith("-"); + final boolean bm = permB.startsWith("-"); if (ap && bp) { return 0; } @@ -39,14 +48,4 @@ public class StringPermissionComparator implements Comparator { } return permA.compareToIgnoreCase(permB); } - - private static StringPermissionComparator instance; - - public static StringPermissionComparator getInstance() { - - if (instance == null) { - instance = new StringPermissionComparator(); - } - return instance; - } } diff --git a/src/main/java/org/anjocaido/groupmanager/utils/Tasks.java b/src/main/java/org/anjocaido/groupmanager/utils/Tasks.java index 7c11d1c..82d1348 100644 --- a/src/main/java/org/anjocaido/groupmanager/utils/Tasks.java +++ b/src/main/java/org/anjocaido/groupmanager/utils/Tasks.java @@ -23,32 +23,38 @@ import org.anjocaido.groupmanager.GroupManager; import org.anjocaido.groupmanager.data.Group; /** - * + * * @author gabrielcouto */ public abstract class Tasks { /** - * Gets the exception stack trace as a string. - * - * @param exception - * @return stack trace as a string + * Appends a string to a file + * + * @param data + * @param file */ - public static String getStackTraceAsString(Exception exception) { - - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - exception.printStackTrace(pw); - return sw.toString(); + public static void appendStringToFile(final String data, final String file) throws IOException { + final FileWriter outStream = new FileWriter("." + System.getProperty("file.separator") + file, true); + final BufferedWriter out = new BufferedWriter(outStream); + data.replaceAll("\n", System.getProperty("line.separator")); + out.append(new SimpleDateFormat("yyyy-MM-dd HH-mm").format(System.currentTimeMillis())); + out.append(System.getProperty("line.separator")); + out.append(data); + out.append(System.getProperty("line.separator")); + out.close(); } - public static void copy(InputStream src, File dst) throws IOException { - - InputStream in = src; - OutputStream out = new FileOutputStream(dst); + public static void copy(final File src, final File dst) throws IOException { + final InputStream in = new FileInputStream(src); + copy(in, dst); + } + public static void copy(final InputStream src, final File dst) throws IOException { + final InputStream in = src; + final OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out - byte[] buf = new byte[1024]; + final byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); @@ -56,58 +62,12 @@ public abstract class Tasks { out.close(); try { in.close(); - } catch (Exception e) { - } - } - - public static void copy(File src, File dst) throws IOException { - - InputStream in = new FileInputStream(src); - copy(in, dst); - } - - /** - * Appends a string to a file - * - * @param data - * @param file - */ - public static void appendStringToFile(String data, String file) throws IOException { - - FileWriter outStream = new FileWriter("." + System.getProperty("file.separator") + file, true); - - BufferedWriter out = new BufferedWriter(outStream); - - data.replaceAll("\n", System.getProperty("line.separator")); - - out.append(new SimpleDateFormat("yyyy-MM-dd HH-mm").format(System.currentTimeMillis())); - out.append(System.getProperty("line.separator")); - out.append(data); - out.append(System.getProperty("line.separator")); - - out.close(); - } - - public static void removeOldFiles(GroupManager gm, File folder) { - - if (folder.isDirectory()) { - long oldTime = System.currentTimeMillis() - (((long) gm.getGMConfig().getBackupDuration() * 60 * 60) * 1000); - for (File olds : folder.listFiles()) { - if (olds.isFile()) { - if (olds.lastModified() < oldTime) { - try { - olds.delete(); - } catch (Exception e) { - } - } - } - } + } catch (final Exception e) { } } public static String getDateString() { - - GregorianCalendar now = new GregorianCalendar(); + final GregorianCalendar now = new GregorianCalendar(); String date = ""; date += now.get(Calendar.DAY_OF_MONTH); date += "-"; @@ -117,38 +77,7 @@ public abstract class Tasks { return date; } - public static String getStringListInString(List list) { - - if (list == null) { - return ""; - } - String result = ""; - for (int i = 0; i < list.size(); i++) { - result += list.get(i); - if (i < list.size() - 1) { - result += ", "; - } - } - return result; - } - - public static String getStringArrayInString(String[] list) { - - if (list == null) { - return ""; - } - String result = ""; - for (int i = 0; i < list.length; i++) { - result += list[i]; - if (i < ((list.length) - 1)) { - result += ", "; - } - } - return result; - } - - public static String getGroupListInString(List list) { - + public static String getGroupListInString(final List list) { if (list == null) { return ""; } @@ -162,8 +91,48 @@ public abstract class Tasks { return result; } - public static String join(String[] arr, String separator) { + /** + * Gets the exception stack trace as a string. + * + * @param exception + * @return stack trace as a string + */ + public static String getStackTraceAsString(final Exception exception) { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + exception.printStackTrace(pw); + return sw.toString(); + } + public static String getStringArrayInString(final String[] list) { + if (list == null) { + return ""; + } + String result = ""; + for (int i = 0; i < list.length; i++) { + result += list[i]; + if (i < ((list.length) - 1)) { + result += ", "; + } + } + return result; + } + + public static String getStringListInString(final List list) { + if (list == null) { + return ""; + } + String result = ""; + for (int i = 0; i < list.size(); i++) { + result += list.get(i); + if (i < list.size() - 1) { + result += ", "; + } + } + return result; + } + + public static String join(final String[] arr, final String separator) { if (arr.length == 0) return ""; String out = arr[0].toString(); @@ -172,4 +141,20 @@ public abstract class Tasks { return out; } + public static void removeOldFiles(final GroupManager gm, final File folder) { + if (folder.isDirectory()) { + final long oldTime = System.currentTimeMillis() - (((long) gm.getGMConfig().getBackupDuration() * 60 * 60) * 1000); + for (final File olds : folder.listFiles()) { + if (olds.isFile()) { + if (olds.lastModified() < oldTime) { + try { + olds.delete(); + } catch (final Exception e) { + } + } + } + } + } + } + } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 92f9af8..a33f454 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: GroupManager -version: ${project.version}(YUMC) +version: ${project.version}-(YUMC) main: org.anjocaido.groupmanager.GroupManager website: http://ess.khhq.net/wiki/Group_Manager description: Provides on-the-fly system for permissions system created by Nijikokun. But all in memory, and with flat-file saving schedule.