汉化大部分条目 清理部分代码...

Signed-off-by: 502647092 <jtb1@163.com>
master
502647092 2016-03-01 20:32:27 +08:00
parent 9a35615a82
commit 678182c644
27 changed files with 1344 additions and 2424 deletions

View File

@ -17,11 +17,10 @@ import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader; import org.yaml.snakeyaml.reader.UnicodeReader;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class GMConfiguration { public class GMConfiguration {
private boolean allowCommandBlocks = false; private boolean allowCommandBlocks = false;
private boolean opOverride = true; private boolean opOverride = true;
private boolean toggleValidate = true; private boolean toggleValidate = true;
@ -29,14 +28,11 @@ public class GMConfiguration {
private Integer backupDuration = 24; private Integer backupDuration = 24;
private String loggerLevel = "OFF"; private String loggerLevel = "OFF";
private Map<String, Object> mirrorsMap; private Map<String, Object> mirrorsMap;
private final GroupManager plugin;
private GroupManager plugin;
private Map<String, Object> GMconfig; private Map<String, Object> GMconfig;
public GMConfiguration(GroupManager plugin) { public GMConfiguration(final GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
/* /*
* Set defaults * Set defaults
*/ */
@ -46,102 +42,118 @@ public class GMConfiguration {
saveInterval = 10; saveInterval = 10;
backupDuration = 24; backupDuration = 24;
loggerLevel = "OFF"; loggerLevel = "OFF";
load(); 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<String, Object> 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") @SuppressWarnings("unchecked")
public void load() { public void load() {
if (!plugin.getDataFolder().exists()) { if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs(); plugin.getDataFolder().mkdirs();
} }
final File configFile = new File(plugin.getDataFolder(), "config.yml");
File configFile = new File(plugin.getDataFolder(), "config.yml");
if (!configFile.exists()) { if (!configFile.exists()) {
try { try {
Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile); 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); GroupManager.logger.log(Level.SEVERE, "Error creating a new config.yml", ex);
} }
} }
final Yaml configYAML = new Yaml(new SafeConstructor());
Yaml configYAML = new Yaml(new SafeConstructor());
try { try {
FileInputStream configInputStream = new FileInputStream(configFile); final FileInputStream configInputStream = new FileInputStream(configFile);
GMconfig = (Map<String, Object>) configYAML.load(new UnicodeReader(configInputStream)); GMconfig = (Map<String, Object>) configYAML.load(new UnicodeReader(configInputStream));
configInputStream.close(); configInputStream.close();
} catch (final Exception ex) {
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), 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. * Read our config settings and store them for reading later.
*/ */
try { try {
Map<String, Object> config = getElement("config", getElement("settings", GMconfig)); final Map<String, Object> config = getElement("config", getElement("settings", GMconfig));
try { try {
allowCommandBlocks = (Boolean) config.get("allow_commandblocks"); 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); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'allow_commandblocks' node. Using default settings", ex);
} }
try { try {
opOverride = (Boolean) config.get("opOverrides"); 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); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'opOverrides' node. Using default settings", ex);
} }
try { try {
toggleValidate = (Boolean) config.get("validate_toggle"); 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); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'validate_toggle' node. Using default settings", ex);
} }
/* /*
* data node for save/backup timers. * data node for save/backup timers.
*/ */
try { try {
Map<String, Object> save = getElement("save", getElement("data", getElement("settings", GMconfig))); final Map<String, Object> save = getElement("save", getElement("data", getElement("settings", GMconfig)));
try { try {
saveInterval = (Integer) save.get("minutes"); 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); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'minutes' node. Using default setting", ex);
} }
try { try {
backupDuration = (Integer) save.get("hours"); 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); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'hours' node. Using default setting", ex);
} }
} catch (final Exception ex) {
} catch (Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'data' node. Using default settings", ex); GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'data' node. Using default settings", ex);
} }
final Object level = ((Map<String, String>) getElement("settings", GMconfig).get("logging")).get("level");
Object level = ((Map<String, String>) getElement("settings", GMconfig).get("logging")).get("level");
if (level instanceof String) if (level instanceof String)
loggerLevel = (String) level; loggerLevel = (String) level;
/* /*
* Store our mirrors map for parsing later. * Store our mirrors map for parsing later.
*/ */
mirrorsMap = (Map<String, Object>) ((Map<String, Object>) GMconfig.get("settings")).get("mirrors"); mirrorsMap = (Map<String, Object>) ((Map<String, Object>) GMconfig.get("settings")).get("mirrors");
if (mirrorsMap == null) if (mirrorsMap == null)
throw new Exception(); throw new Exception();
} catch (final Exception ex) {
} catch (Exception ex) {
/* /*
* Flag the error and use defaults * Flag the error and use defaults
*/ */
GroupManager.logger.log(Level.SEVERE, "There are errors in your config.yml. Using default settings", ex); GroupManager.logger.log(Level.SEVERE, "There are errors in your config.yml. Using default settings", ex);
mirrorsMap = new HashMap<String, Object>(); mirrorsMap = new HashMap<String, Object>();
} }
// Setup defaults // Setup defaults
@ -150,59 +162,10 @@ public class GMConfiguration {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, Object> getElement(String element, Map<String, Object> map) { private Map<String, Object> getElement(final String element, final Map<String, Object> map) {
if (!map.containsKey(element)) { if (!map.containsKey(element)) {
throw new IllegalArgumentException("The config.yml has no '" + element + ".\n"); throw new IllegalArgumentException("The config.yml has no '" + element + ".\n");
} }
return (Map<String, Object>) map.get(element); return (Map<String, Object>) 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<String, Object> getMirrorsMap() {
if (!mirrorsMap.isEmpty()) {
return mirrorsMap;
}
return null;
}
} }

View File

@ -25,35 +25,142 @@ import org.yaml.snakeyaml.reader.UnicodeReader;
/** /**
* @author ElgarL * @author ElgarL
* *
*/ */
public class GlobalGroups { public class GlobalGroups {
private final GroupManager plugin;
private GroupManager plugin;
// private Yaml GGroups; // private Yaml GGroups;
private final Map<String, Group> groups = Collections.synchronizedMap(new HashMap<String, Group>()); private final Map<String, Group> groups = Collections.synchronizedMap(new HashMap<String, Group>());
protected long timeStampGroups = 0; protected long timeStampGroups = 0;
protected boolean haveGroupsChanged = false; protected boolean haveGroupsChanged = false;
protected File GlobalGroupsFile = null; protected File GlobalGroupsFile = null;
public GlobalGroups(GroupManager plugin) { public GlobalGroups(final GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
load(); 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<String> 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 * @return the haveGroupsChanged
*/ */
public boolean haveGroupsChanged() { public boolean haveGroupsChanged() {
if (this.haveGroupsChanged) { if (this.haveGroupsChanged) {
return true; return true;
} }
synchronized (groups) { synchronized (groups) {
for (Group g : groups.values()) { for (final Group g : groups.values()) {
if (g.isChanged()) { if (g.isChanged()) {
return true; return true;
} }
@ -62,85 +169,48 @@ public class GlobalGroups {
return false; 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") @SuppressWarnings("unchecked")
public void load() { public void load() {
final Yaml GGroupYAML = new Yaml(new SafeConstructor());
Yaml GGroupYAML = new Yaml(new SafeConstructor());
Map<String, Object> GGroups; Map<String, Object> GGroups;
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
// READ globalGroups FILE // READ globalGroups FILE
if (GlobalGroupsFile == null) if (GlobalGroupsFile == null)
GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml"); GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml");
if (!GlobalGroupsFile.exists()) { if (!GlobalGroupsFile.exists()) {
try { try {
// Create a new file if it doesn't exist. // Create a new file if it doesn't exist.
Tasks.copy(plugin.getResourceAsStream("globalgroups.yml"), GlobalGroupsFile); Tasks.copy(plugin.getResourceAsStream("globalgroups.yml"), GlobalGroupsFile);
} catch (IOException ex) { } catch (final IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex); GroupManager.logger.log(Level.SEVERE, null, ex);
} }
} }
/* /*
* Load the YAML file. * Load the YAML file.
*/ */
try { try {
FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile); final FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile);
GGroups = (Map<String, Object>) GGroupYAML.load(new UnicodeReader(groupsInputStream)); GGroups = (Map<String, Object>) GGroupYAML.load(new UnicodeReader(groupsInputStream));
groupsInputStream.close(); groupsInputStream.close();
} catch (Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + GlobalGroupsFile.getPath(), ex); throw new IllegalArgumentException("下列文件无法被解析.\n" + GlobalGroupsFile.getPath(), ex);
} }
// Clear out old groups // Clear out old groups
resetGlobalGroups(); resetGlobalGroups();
if (!GGroups.keySet().isEmpty()) { if (!GGroups.keySet().isEmpty()) {
// Read all global groups // Read all global groups
Map<String, Object> allGroups = new HashMap<String, Object>(); Map<String, Object> allGroups = new HashMap<String, Object>();
try { try {
allGroups = (Map<String, Object>) GGroups.get("groups"); allGroups = (Map<String, Object>) GGroups.get("groups");
} catch (Exception ex) { } catch (final Exception ex) {
// ex.printStackTrace(); // 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. // Load each groups permissions list.
if (allGroups != null) { if (allGroups != null) {
final Iterator<String> groupItr = allGroups.keySet().iterator();
Iterator<String> groupItr = allGroups.keySet().iterator();
String groupName; String groupName;
Integer groupCount = 0; Integer groupCount = 0;
/* /*
* loop each group entry * loop each group entry
* and read it's data. * and read it's data.
@ -150,39 +220,35 @@ public class GlobalGroups {
groupCount++; groupCount++;
// Attempt to fetch the next group name. // Attempt to fetch the next group name.
groupName = groupItr.next(); 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); throw new IllegalArgumentException("Invalid group name for GlobalGroup entry (" + groupCount + ") in file: " + GlobalGroupsFile.getPath(), ex);
} }
/* /*
* Create a new group with this name. * Create a new group with this name.
*/ */
Group newGroup = new Group(groupName.toLowerCase()); final Group newGroup = new Group(groupName.toLowerCase());
Object element; Object element;
// Permission nodes // Permission nodes
try { try {
element = ((Map<String, Object>) allGroups.get(groupName)).get("permissions"); element = ((Map<String, Object>) allGroups.get(groupName)).get("permissions");
} catch (Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("The GlobalGroup ' " + groupName + "' is formatted incorrectly: ", ex); throw new IllegalArgumentException("The GlobalGroup ' " + groupName + "' is formatted incorrectly: ", ex);
} }
if (element != null) if (element != null)
if (element instanceof List) { if (element instanceof List) {
try { try {
for (String node : (List<String>) element) { for (final String node : (List<String>) element) {
if ((node != null) && !node.isEmpty()) if ((node != null) && !node.isEmpty())
newGroup.addPermission(node); newGroup.addPermission(node);
} }
} catch (ClassCastException ex) { } catch (final ClassCastException ex) {
throw new IllegalArgumentException("Invalid permission node for global group: " + groupName, ex); throw new IllegalArgumentException("不注册的权限节点 在全局组: " + groupName, ex);
} }
} else if (element instanceof String) { } else if (element instanceof String) {
if ((element != null) && !((String) element).isEmpty()) if ((element != null) && !((String) element).isEmpty())
newGroup.addPermission((String) element); newGroup.addPermission((String) element);
} else } else
throw new IllegalArgumentException("Unknown type of permission node for global group: " + groupName); throw new IllegalArgumentException("未知的权限类型 在全局组: " + groupName);
// // Info nodes // // Info nodes
// try { // try {
// element = ((Map<String, Object>)allGroups.get(groupName)).get("info"); // element = ((Map<String, Object>)allGroups.get(groupName)).get("info");
@ -199,42 +265,103 @@ public class GlobalGroups {
// newGroup.setVariables(vars); // newGroup.setVariables(vars);
// } else // } else
// throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName); // throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName);
// Push a new group // Push a new group
addGroup(newGroup); addGroup(newGroup);
} }
} }
removeGroupsChangedFlag(); removeGroupsChangedFlag();
} }
setTimeStampGroups(GlobalGroupsFile.lastModified()); setTimeStampGroups(GlobalGroupsFile.lastModified());
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
// GlobalGroupsFile = null; // 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<String> 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 * Write the globalgroups.yml file
*/ */
public void writeGroups(final boolean overwrite) {
public void writeGroups(boolean overwrite) {
// File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml"); // File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml");
if (haveGroupsChanged()) { if (haveGroupsChanged()) {
if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) { if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) {
Map<String, Object> root = new HashMap<String, Object>(); final Map<String, Object> root = new HashMap<String, Object>();
final Map<String, Object> groupsMap = new HashMap<String, Object>();
Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap); root.put("groups", groupsMap);
synchronized (groups) { synchronized (groups) {
for (String groupKey : groups.keySet()) { for (final String groupKey : groups.keySet()) {
Group group = groups.get(groupKey); final Group group = groups.get(groupKey);
// Group header // Group header
Map<String, Object> aGroupMap = new HashMap<String, Object>(); final Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap); groupsMap.put(group.getName(), aGroupMap);
// // Info nodes // // Info nodes
// Map<String, Object> infoMap = new HashMap<String, Object>(); // Map<String, Object> infoMap = new HashMap<String, Object>();
// aGroupMap.put("info", infoMap); // aGroupMap.put("info", infoMap);
@ -242,20 +369,18 @@ public class GlobalGroups {
// for (String infoKey : group.getVariables().getVarKeyList()) { // for (String infoKey : group.getVariables().getVarKeyList()) {
// infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); // infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
// } // }
// Permission nodes // Permission nodes
aGroupMap.put("permissions", group.getPermissionList()); aGroupMap.put("permissions", group.getPermissionList());
} }
} }
if (!root.isEmpty()) { if (!root.isEmpty()) {
DumperOptions opt = new DumperOptions(); final DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt); final Yaml yaml = new Yaml(opt);
try { try {
yaml.dump(root, new OutputStreamWriter(new FileOutputStream(GlobalGroupsFile), "UTF-8")); yaml.dump(root, new OutputStreamWriter(new FileOutputStream(GlobalGroupsFile), "UTF-8"));
} catch (UnsupportedEncodingException ex) { } catch (final UnsupportedEncodingException ex) {
} catch (FileNotFoundException ex) { } catch (final FileNotFoundException ex) {
} }
} }
setTimeStampGroups(GlobalGroupsFile.lastModified()); setTimeStampGroups(GlobalGroupsFile.lastModified());
@ -274,210 +399,27 @@ public class GlobalGroups {
load(); load();
} }
} }
} }
/** /**
* Backup the BlobalGroups file * Backup the BlobalGroups file
* *
* @param w * @param w
*/ */
private void backupFile() { private void backupFile() {
final File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
try { try {
Tasks.copy(GlobalGroupsFile, backupFile); Tasks.copy(GlobalGroupsFile, backupFile);
} catch (IOException ex) { } catch (final IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex); GroupManager.logger.log(Level.SEVERE, null, ex);
} }
} }
/** /**
* Adds a group, or replaces an existing one. * @param timeStampGroups
* * the timeStampGroups to set
* @param groupToAdd
*/ */
public void addGroup(Group groupToAdd) { protected void setTimeStampGroups(final long timeStampGroups) {
this.timeStampGroups = timeStampGroups;
// 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);
} }
/**
* 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<String> 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<String> 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();
}
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,27 +3,23 @@ package org.anjocaido.groupmanager.Tasks;
import org.anjocaido.groupmanager.GroupManager; import org.anjocaido.groupmanager.GroupManager;
/* /*
* *
* Created by ElgarL * Created by ElgarL
*/ */
public class BukkitPermsUpdateTask implements Runnable { public class BukkitPermsUpdateTask implements Runnable {
public BukkitPermsUpdateTask() { public BukkitPermsUpdateTask() {
super(); super();
} }
@Override @Override
public void run() { public void run() {
// Signal loaded and update BukkitPermissions. // Signal loaded and update BukkitPermissions.
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
GroupManager.BukkitPermissions.collectPermissions(); GroupManager.BukkitPermissions.collectPermissions();
GroupManager.BukkitPermissions.updateAllPlayers(); GroupManager.BukkitPermissions.updateAllPlayers();
GroupManager.logger.info("权限已更新!");
GroupManager.logger.info("Bukkit Permissions Updated!");
} }
} }

View File

@ -13,39 +13,44 @@ import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.utils.StringPermissionComparator; import org.anjocaido.groupmanager.utils.StringPermissionComparator;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class DataUnit { public abstract class DataUnit {
private WorldDataHolder dataSource; private WorldDataHolder dataSource;
private String uUID; private final String uUID;
private String lastName; private String lastName;
private boolean changed, sorted = false; private boolean changed, sorted = false;
private List<String> permissions = Collections.unmodifiableList(Collections.<String> emptyList()); private List<String> permissions = Collections.unmodifiableList(Collections.<String> 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.dataSource = dataSource;
this.uUID = name; this.uUID = name;
} }
public DataUnit(String name) { public void addPermission(final String permission) {
if (!hasSamePermissionNode(permission)) {
this.uUID = name; final List<String> clone = new ArrayList<String>(permissions);
clone.add(permission);
permissions = Collections.unmodifiableList(clone);
}
flagAsChanged();
} }
/** /**
* Every group is matched only by their names and DataSources names. * Every group is matched only by their names and DataSources names.
* *
* @param o * @param o
* @return true if they are equal. false if not. * @return true if they are equal. false if not.
*/ */
@Override @Override
public boolean equals(Object o) { public boolean equals(final Object o) {
if (o instanceof DataUnit) { if (o instanceof DataUnit) {
DataUnit go = (DataUnit) o; final DataUnit go = (DataUnit) o;
if (this.getUUID().equalsIgnoreCase(go.getUUID())) { if (this.getUUID().equalsIgnoreCase(go.getUUID())) {
// Global Group match. // Global Group match.
if (this.dataSource == null && go.getDataSource() == null) if (this.dataSource == null && go.getDataSource() == null)
@ -64,68 +69,13 @@ public abstract class DataUnit {
return false; 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() { public void flagAsChanged() {
final WorldDataHolder testSource = getDataSource();
WorldDataHolder testSource = getDataSource();
String source = ""; String source = "";
if (testSource == null) if (testSource == null)
source = "GlobalGroups"; source = "GlobalGroups";
else else
source = testSource.getName(); source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as changed!"); GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as changed!");
// for(StackTraceElement st: Thread.currentThread().getStackTrace()){ // for(StackTraceElement st: Thread.currentThread().getStackTrace()){
// GroupManager.logger.finest(st.toString()); // GroupManager.logger.finest(st.toString());
@ -134,53 +84,36 @@ public abstract class DataUnit {
changed = true; changed = true;
} }
public boolean isChanged() {
return changed;
}
public void flagAsSaved() { public void flagAsSaved() {
final WorldDataHolder testSource = getDataSource();
WorldDataHolder testSource = getDataSource();
String source = ""; String source = "";
if (testSource == null) if (testSource == null)
source = "GlobalGroups"; source = "GlobalGroups";
else else
source = testSource.getName(); source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as saved!"); GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getUUID() + " flagged as saved!");
changed = false; changed = false;
} }
public boolean hasSamePermissionNode(String permission) { /**
* Get the current worldDataHolder this object is pointing to
return permissions.contains(permission); *
* @return the dataSource
*/
public WorldDataHolder getDataSource() {
return dataSource;
} }
public void addPermission(String permission) { public String getLastName() {
if (uUID.length() < 36)
if (!hasSamePermissionNode(permission)) { return this.uUID;
List<String> clone = new ArrayList<String>(permissions); return this.lastName;
clone.add(permission);
permissions = Collections.unmodifiableList(clone);
}
flagAsChanged();
}
public boolean removePermission(String permission) {
flagAsChanged();
List<String> clone = new ArrayList<String>(permissions);
boolean ret = clone.remove(permission);
permissions = Collections.unmodifiableList(clone);
return ret;
} }
/** /**
* Use this only to list permissions. * Use this only to list permissions.
* You can't edit the permissions using the returned ArrayList instance * You can't edit the permissions using the returned ArrayList instance
* *
* @return a copy of the permission list * @return a copy of the permission list
*/ */
public List<String> getPermissionList() { public List<String> getPermissionList() {
@ -188,15 +121,56 @@ public abstract class DataUnit {
return permissions; 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; return this.sorted;
} }
public void sortPermissions() { public boolean removePermission(final String permission) {
flagAsChanged();
final List<String> clone = new ArrayList<String>(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()) { if (!isSorted()) {
List<String> clone = new ArrayList<String>(permissions); final List<String> clone = new ArrayList<String>(permissions);
Collections.sort(clone, StringPermissionComparator.getInstance()); Collections.sort(clone, StringPermissionComparator.getInstance());
permissions = Collections.unmodifiableList(clone); permissions = Collections.unmodifiableList(clone);
sorted = true; sorted = true;

View File

@ -18,7 +18,6 @@ import org.anjocaido.groupmanager.events.GMGroupEvent.Action;
* @author gabrielcouto/ElgarL * @author gabrielcouto/ElgarL
*/ */
public class Group extends DataUnit implements Cloneable { public class Group extends DataUnit implements Cloneable {
/** /**
* The group it inherits DIRECTLY! * The group it inherits DIRECTLY!
*/ */
@ -36,7 +35,6 @@ public class Group extends DataUnit implements Cloneable {
* @param name * @param name
*/ */
public Group(final String name) { public Group(final String name) {
super(name); super(name);
} }
@ -46,7 +44,6 @@ public class Group extends DataUnit implements Cloneable {
* @param name * @param name
*/ */
public Group(final WorldDataHolder source, final String name) { public Group(final WorldDataHolder source, final String name) {
super(source, name); super(source, name);
} }
@ -55,7 +52,6 @@ public class Group extends DataUnit implements Cloneable {
* the inherits to set * the inherits to set
*/ */
public void addInherits(final Group inherit) { public void addInherits(final Group inherit) {
if (!isGlobal()) { if (!isGlobal()) {
if (!this.getDataSource().groupExists(inherit.getName())) { if (!this.getDataSource().groupExists(inherit.getName())) {
getDataSource().addGroup(inherit); getDataSource().addGroup(inherit);
@ -80,16 +76,13 @@ public class Group extends DataUnit implements Cloneable {
*/ */
@Override @Override
public Group clone() { public Group clone() {
Group clone; Group clone;
if (isGlobal()) { if (isGlobal()) {
clone = new Group(this.getName()); clone = new Group(this.getName());
} else { } else {
clone = new Group(getDataSource(), this.getName()); clone = new Group(getDataSource(), this.getName());
clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections.<String> emptyList()) : Collections.unmodifiableList(new ArrayList<String>(this.getInherits())); clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections.<String> emptyList()) : Collections.unmodifiableList(new ArrayList<String>(this.getInherits()));
} }
for (final String perm : this.getPermissionList()) { for (final String perm : this.getPermissionList()) {
clone.addPermission(perm); clone.addPermission(perm);
} }
@ -105,13 +98,10 @@ public class Group extends DataUnit implements Cloneable {
* @return Null or Clone * @return Null or Clone
*/ */
public Group clone(final WorldDataHolder dataSource) { public Group clone(final WorldDataHolder dataSource) {
if (dataSource.groupExists(this.getName())) { if (dataSource.groupExists(this.getName())) {
return null; return null;
} }
final Group clone = dataSource.createGroup(this.getName()); final Group clone = dataSource.createGroup(this.getName());
// Don't add inheritance for GlobalGroups // Don't add inheritance for GlobalGroups
if (!isGlobal()) { if (!isGlobal()) {
clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections.<String> emptyList()) : Collections.unmodifiableList(new ArrayList<String>(this.getInherits())); clone.inherits = this.getInherits().isEmpty() ? Collections.unmodifiableList(Collections.<String> emptyList()) : Collections.unmodifiableList(new ArrayList<String>(this.getInherits()));
@ -139,7 +129,6 @@ public class Group extends DataUnit implements Cloneable {
* @return the name * @return the name
*/ */
public String getName() { public String getName() {
return this.getUUID(); return this.getUUID();
} }
@ -147,7 +136,6 @@ public class Group extends DataUnit implements Cloneable {
* @return the variables * @return the variables
*/ */
public GroupVariables getVariables() { public GroupVariables getVariables() {
return variables; return variables;
} }
@ -157,12 +145,10 @@ public class Group extends DataUnit implements Cloneable {
* @return true if this is a global group * @return true if this is a global group
*/ */
public boolean isGlobal() { public boolean isGlobal() {
return (getDataSource() == null); return (getDataSource() == null);
} }
public boolean removeInherits(final String inherit) { public boolean removeInherits(final String inherit) {
if (!isGlobal()) { if (!isGlobal()) {
if (this.inherits.contains(inherit.toLowerCase())) { if (this.inherits.contains(inherit.toLowerCase())) {
final List<String> clone = new ArrayList<String>(inherits); final List<String> clone = new ArrayList<String>(inherits);
@ -181,7 +167,6 @@ public class Group extends DataUnit implements Cloneable {
* @param varList * @param varList
*/ */
public void setVariables(final Map<String, Object> varList) { public void setVariables(final Map<String, Object> varList) {
if (!isGlobal()) { if (!isGlobal()) {
final GroupVariables temp = new GroupVariables(this, varList); final GroupVariables temp = new GroupVariables(this, varList);
variables.clearVars(); variables.clearVars();

View File

@ -11,7 +11,6 @@ import java.util.Map;
* @author gabrielcouto * @author gabrielcouto
*/ */
public class GroupVariables extends Variables implements Cloneable { public class GroupVariables extends Variables implements Cloneable {
private final Group owner; private final Group owner;
public GroupVariables(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<String, Object> varList) { public GroupVariables(final Group owner, final Map<String, Object> varList) {
super(owner); super(owner);
variables.clear(); variables.clear();
variables.putAll(varList); variables.putAll(varList);
@ -32,13 +30,11 @@ public class GroupVariables extends Variables implements Cloneable {
owner.flagAsChanged(); owner.flagAsChanged();
} }
// thisGrp.prefix = infoNode.get("prefix").toString(); // thisGrp.prefix = infoNode.get("prefix").toString();
if (variables.get("suffix") == null) { if (variables.get("suffix") == null) {
variables.put("suffix", ""); variables.put("suffix", "");
owner.flagAsChanged(); owner.flagAsChanged();
} }
// thisGrp.suffix = infoNode.get("suffix").toString(); // thisGrp.suffix = infoNode.get("suffix").toString();
if (variables.get("build") == null) { if (variables.get("build") == null) {
variables.put("build", false); variables.put("build", false);
owner.flagAsChanged(); owner.flagAsChanged();
@ -51,7 +47,6 @@ public class GroupVariables extends Variables implements Cloneable {
*/ */
@Override @Override
public Group getOwner() { public Group getOwner() {
return owner; return owner;
} }
@ -62,7 +57,6 @@ public class GroupVariables extends Variables implements Cloneable {
*/ */
@Override @Override
public void removeVar(final String name) { public void removeVar(final String name) {
try { try {
this.variables.remove(name); this.variables.remove(name);
} catch (final Exception e) { } catch (final Exception e) {
@ -83,7 +77,6 @@ public class GroupVariables extends Variables implements Cloneable {
* @return GroupVariables clone * @return GroupVariables clone
*/ */
protected GroupVariables clone(final Group newOwner) { protected GroupVariables clone(final Group newOwner) {
final GroupVariables clone = new GroupVariables(newOwner); final GroupVariables clone = new GroupVariables(newOwner);
synchronized (variables) { synchronized (variables) {
for (final String key : variables.keySet()) { for (final String key : variables.keySet()) {

View File

@ -21,7 +21,6 @@ import org.bukkit.entity.Player;
* @author gabrielcouto/ElgarL * @author gabrielcouto/ElgarL
*/ */
public class User extends DataUnit implements Cloneable { public class User extends DataUnit implements Cloneable {
private String group = null; private String group = null;
private final List<String> subGroups = Collections.synchronizedList(new ArrayList<String>()); private final List<String> subGroups = Collections.synchronizedList(new ArrayList<String>());
/** /**
@ -36,13 +35,11 @@ public class User extends DataUnit implements Cloneable {
* @param name * @param name
*/ */
public User(final WorldDataHolder source, final String name) { public User(final WorldDataHolder source, final String name) {
super(source, name); super(source, name);
this.group = source.getDefaultGroup().getName(); this.group = source.getDefaultGroup().getName();
} }
public boolean addSubGroup(final Group subGroup) { public boolean addSubGroup(final Group subGroup) {
// Don't allow adding a subgroup if it's already set as the primary. // Don't allow adding a subgroup if it's already set as the primary.
if (this.group.equalsIgnoreCase(subGroup.getName())) { if (this.group.equalsIgnoreCase(subGroup.getName())) {
return false; return false;
@ -50,12 +47,10 @@ public class User extends DataUnit implements Cloneable {
// User already has this subgroup // User already has this subgroup
if (containsSubGroup(subGroup)) if (containsSubGroup(subGroup))
return false; return false;
// If the group doesn't exists add it // If the group doesn't exists add it
if (!this.getDataSource().groupExists(subGroup.getName())) { if (!this.getDataSource().groupExists(subGroup.getName())) {
getDataSource().addGroup(subGroup); getDataSource().addGroup(subGroup);
} }
subGroups.add(subGroup.getName()); subGroups.add(subGroup.getName());
flagAsChanged(); flagAsChanged();
if (GroupManager.isLoaded()) { if (GroupManager.isLoaded()) {
@ -64,7 +59,6 @@ public class User extends DataUnit implements Cloneable {
GroupManager.getGMEventHandler().callEvent(this, Action.USER_SUBGROUP_CHANGED); GroupManager.getGMEventHandler().callEvent(this, Action.USER_SUBGROUP_CHANGED);
} }
return true; return true;
// subGroup = getDataSource().getGroup(subGroup.getName()); // subGroup = getDataSource().getGroup(subGroup.getName());
// removeSubGroup(subGroup); // removeSubGroup(subGroup);
// subGroups.add(subGroup.getName()); // subGroups.add(subGroup.getName());
@ -76,13 +70,10 @@ public class User extends DataUnit implements Cloneable {
*/ */
@Override @Override
public User clone() { public User clone() {
final User clone = new User(getDataSource(), this.getLastName()); final User clone = new User(getDataSource(), this.getLastName());
clone.group = this.group; clone.group = this.group;
// Clone all subgroups. // Clone all subgroups.
clone.subGroups.addAll(this.subGroupListStringCopy()); clone.subGroups.addAll(this.subGroupListStringCopy());
for (final String perm : this.getPermissionList()) { for (final String perm : this.getPermissionList()) {
clone.addPermission(perm); clone.addPermission(perm);
} }
@ -92,24 +83,17 @@ public class User extends DataUnit implements Cloneable {
} }
public User clone(final String uUID, final String CurrentName) { public User clone(final String uUID, final String CurrentName) {
final User clone = this.getDataSource().createUser(uUID); final User clone = this.getDataSource().createUser(uUID);
clone.setLastName(CurrentName); clone.setLastName(CurrentName);
// Set the group silently. // Set the group silently.
clone.setGroup(this.getDataSource().getGroup(this.getGroupName()), false); clone.setGroup(this.getDataSource().getGroup(this.getGroupName()), false);
// Clone all subgroups. // Clone all subgroups.
clone.subGroups.addAll(this.subGroupListStringCopy()); clone.subGroups.addAll(this.subGroupListStringCopy());
for (final String perm : this.getPermissionList()) { for (final String perm : this.getPermissionList()) {
clone.addPermission(perm); clone.addPermission(perm);
} }
clone.variables = this.variables.clone(this); clone.variables = this.variables.clone(this);
clone.flagAsChanged(); clone.flagAsChanged();
return clone; return clone;
} }
@ -120,38 +104,30 @@ public class User extends DataUnit implements Cloneable {
* @return null if given dataSource already contains the same user * @return null if given dataSource already contains the same user
*/ */
public User clone(final WorldDataHolder dataSource) { public User clone(final WorldDataHolder dataSource) {
if (dataSource.isUserDeclared(this.getUUID())) { if (dataSource.isUserDeclared(this.getUUID())) {
return null; return null;
} }
final User clone = dataSource.createUser(this.getUUID()); final User clone = dataSource.createUser(this.getUUID());
if (dataSource.getGroup(group) == null) { if (dataSource.getGroup(group) == null) {
clone.setGroup(dataSource.getDefaultGroup()); clone.setGroup(dataSource.getDefaultGroup());
} else { } else {
clone.setGroup(dataSource.getGroup(this.getGroupName())); clone.setGroup(dataSource.getGroup(this.getGroupName()));
} }
// Clone all subgroups. // Clone all subgroups.
clone.subGroups.addAll(this.subGroupListStringCopy()); clone.subGroups.addAll(this.subGroupListStringCopy());
for (final String perm : this.getPermissionList()) { for (final String perm : this.getPermissionList()) {
clone.addPermission(perm); clone.addPermission(perm);
} }
clone.variables = this.variables.clone(this); clone.variables = this.variables.clone(this);
clone.flagAsChanged(); clone.flagAsChanged();
return clone; return clone;
} }
public boolean containsSubGroup(final Group subGroup) { public boolean containsSubGroup(final Group subGroup) {
return subGroups.contains(subGroup.getName()); return subGroups.contains(subGroup.getName());
} }
public Player getBukkitPlayer() { public Player getBukkitPlayer() {
if (bukkitPlayer == null) { if (bukkitPlayer == null) {
bukkitPlayer = Bukkit.getPlayer(this.getLastName()); bukkitPlayer = Bukkit.getPlayer(this.getLastName());
} }
@ -159,7 +135,6 @@ public class User extends DataUnit implements Cloneable {
} }
public Group getGroup() { public Group getGroup() {
Group result = getDataSource().getGroup(group); Group result = getDataSource().getGroup(group);
if (result == null) { if (result == null) {
this.setGroup(getDataSource().getDefaultGroup()); this.setGroup(getDataSource().getDefaultGroup());
@ -172,7 +147,6 @@ public class User extends DataUnit implements Cloneable {
* @return the group * @return the group
*/ */
public String getGroupName() { public String getGroupName() {
final Group result = getDataSource().getGroup(group); final Group result = getDataSource().getGroup(group);
if (result == null) { if (result == null) {
group = getDataSource().getDefaultGroup().getName(); group = getDataSource().getDefaultGroup().getName();
@ -188,26 +162,21 @@ public class User extends DataUnit implements Cloneable {
*/ */
@Deprecated @Deprecated
public String getName() { public String getName() {
return this.getLastName(); return this.getLastName();
} }
/** /**
* @return the variables * @return the variables
*/ */
public UserVariables getVariables() { public UserVariables getVariables() {
return variables; return variables;
} }
public boolean isSubGroupsEmpty() { public boolean isSubGroupsEmpty() {
return subGroups.isEmpty(); return subGroups.isEmpty();
} }
public boolean removeSubGroup(final Group subGroup) { public boolean removeSubGroup(final Group subGroup) {
try { try {
if (subGroups.remove(subGroup.getName())) { if (subGroups.remove(subGroup.getName())) {
flagAsChanged(); flagAsChanged();
@ -227,7 +196,6 @@ public class User extends DataUnit implements Cloneable {
* the group to set * the group to set
*/ */
public void setGroup(final Group group) { public void setGroup(final Group group) {
setGroup(group, true); setGroup(group, true);
} }
@ -239,7 +207,6 @@ public class User extends DataUnit implements Cloneable {
* *
*/ */
public void setGroup(Group group, final Boolean updatePerms) { public void setGroup(Group group, final Boolean updatePerms) {
if (!this.getDataSource().groupExists(group.getName())) { if (!this.getDataSource().groupExists(group.getName())) {
getDataSource().addGroup(group); getDataSource().addGroup(group);
} }
@ -250,17 +217,14 @@ public class User extends DataUnit implements Cloneable {
if (GroupManager.isLoaded()) { if (GroupManager.isLoaded()) {
if (!GroupManager.BukkitPermissions.isPlayer_join() && (updatePerms)) if (!GroupManager.BukkitPermissions.isPlayer_join() && (updatePerms))
GroupManager.BukkitPermissions.updatePlayer(getBukkitPlayer()); GroupManager.BukkitPermissions.updatePlayer(getBukkitPlayer());
// Do we notify of the group change? // Do we notify of the group change?
final String defaultGroupName = getDataSource().getDefaultGroup().getName(); final String defaultGroupName = getDataSource().getDefaultGroup().getName();
// if we were not in the default group // if we were not in the default group
// or we were in the default group and the move is to a different // or we were in the default group and the move is to a different
// group. // group.
final boolean notify = (!oldGroup.equalsIgnoreCase(defaultGroupName)) || ((oldGroup.equalsIgnoreCase(defaultGroupName)) && (!this.group.equalsIgnoreCase(defaultGroupName))); final boolean notify = (!oldGroup.equalsIgnoreCase(defaultGroupName)) || ((oldGroup.equalsIgnoreCase(defaultGroupName)) && (!this.group.equalsIgnoreCase(defaultGroupName)));
if (notify) if (notify)
GroupManager.notify(this.getLastName(), String.format(" moved to the group %s in %s.", group.getName(), this.getDataSource().getName())); GroupManager.notify(this.getLastName(), String.format(" moved to the group %s in %s.", group.getName(), this.getDataSource().getName()));
if (updatePerms) if (updatePerms)
GroupManager.getGMEventHandler().callEvent(this, Action.USER_GROUP_CHANGED); GroupManager.getGMEventHandler().callEvent(this, Action.USER_GROUP_CHANGED);
} }
@ -271,7 +235,6 @@ public class User extends DataUnit implements Cloneable {
* @param varList * @param varList
*/ */
public void setVariables(final Map<String, Object> varList) { public void setVariables(final Map<String, Object> varList) {
// UserVariables temp = new UserVariables(this, varList); // UserVariables temp = new UserVariables(this, varList);
variables.clearVars(); variables.clearVars();
for (final String key : varList.keySet()) { for (final String key : varList.keySet()) {
@ -286,7 +249,6 @@ public class User extends DataUnit implements Cloneable {
} }
public ArrayList<Group> subGroupListCopy() { public ArrayList<Group> subGroupListCopy() {
final ArrayList<Group> val = new ArrayList<Group>(); final ArrayList<Group> val = new ArrayList<Group>();
synchronized (subGroups) { synchronized (subGroups) {
for (final String gstr : subGroups) { for (final String gstr : subGroups) {
@ -308,12 +270,10 @@ public class User extends DataUnit implements Cloneable {
} }
public int subGroupsSize() { public int subGroupsSize() {
return subGroups.size(); return subGroups.size();
} }
public User updatePlayer(final Player player) { public User updatePlayer(final Player player) {
bukkitPlayer = player; bukkitPlayer = player;
return this; return this;
} }

View File

@ -11,11 +11,9 @@ import java.util.Map;
* @author gabrielcouto * @author gabrielcouto
*/ */
public class UserVariables extends Variables { public class UserVariables extends Variables {
private final User owner; private final User owner;
public UserVariables(final User owner) { public UserVariables(final User owner) {
super(owner); super(owner);
this.owner = owner; this.owner = owner;
} }
@ -32,7 +30,6 @@ public class UserVariables extends Variables {
*/ */
@Override @Override
public User getOwner() { public User getOwner() {
return owner; return owner;
} }
@ -42,7 +39,6 @@ public class UserVariables extends Variables {
* @return UserVariables clone * @return UserVariables clone
*/ */
protected UserVariables clone(final User newOwner) { protected UserVariables clone(final User newOwner) {
final UserVariables clone = new UserVariables(newOwner); final UserVariables clone = new UserVariables(newOwner);
synchronized (variables) { synchronized (variables) {
for (final String key : variables.keySet()) { for (final String key : variables.keySet()) {

View File

@ -15,32 +15,48 @@ import java.util.Map;
* prefix * prefix
* suffix * suffix
* build * build
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class Variables implements Cloneable { public abstract class Variables implements Cloneable {
private final DataUnit owner;
private DataUnit owner;
protected final Map<String, Object> variables = Collections.synchronizedMap(new HashMap<String, Object>()); protected final Map<String, Object> variables = Collections.synchronizedMap(new HashMap<String, Object>());
public Variables(DataUnit owner) { public Variables(final DataUnit owner) {
this.owner = 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. * Add var to the the INFO node.
* examples: * examples:
* addVar("build",true); * addVar("build",true);
* addVar("prefix","c"); * addVar("prefix","c");
* *
* @param name * @param name
* key name of the var * key name of the var
* @param o * @param o
* the object value of the var * 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) { if (o == null) {
return; return;
} }
@ -51,82 +67,72 @@ public abstract class Variables implements Cloneable {
owner.flagAsChanged(); owner.flagAsChanged();
} }
/** public void clearVars() {
* Returns the object inside the var variables.clear();
* owner.flagAsChanged();
* @param name
* @return a Object if exists. null if doesn't exists
*/
public Object getVarObject(String name) {
return variables.get(name);
} }
/** /**
* Get the String value for the given var name * @return the owner
*
* @param name
* the var key name
* @return "" if null. or the toString() value of object
*/ */
public String getVarString(String name) { public DataUnit getOwner() {
return owner;
Object o = variables.get(name);
try {
return o == null ? "" : o.toString();
} catch (Exception e) {
return "";
}
} }
/** /**
* * Returns the quantity of vars this is holding
*
* @return the number of vars
*/
public int getSize() {
return variables.size();
}
/**
*
* @param name * @param name
* @return false if null. or a Boolean.parseBoolean of the string * @return false if null. or a Boolean.parseBoolean of the string
*/ */
public Boolean getVarBoolean(String name) { public Boolean getVarBoolean(final String name) {
final Object o = variables.get(name);
Object o = variables.get(name);
try { try {
return o == null ? false : Boolean.parseBoolean(o.toString()); return o == null ? false : Boolean.parseBoolean(o.toString());
} catch (Exception e) { } catch (final Exception e) {
return false; 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 * @param name
* @return -1 if null. or a parseDouble of the string * @return -1 if null. or a parseDouble of the string
*/ */
public Double getVarDouble(String name) { public Double getVarDouble(final String name) {
final Object o = variables.get(name);
Object o = variables.get(name);
try { try {
return o == null ? -1.0D : Double.parseDouble(o.toString()); return o == null ? -1.0D : Double.parseDouble(o.toString());
} catch (Exception e) { } catch (final Exception e) {
return -1.0D; 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 * All variable keys this is holding
* *
* @return Set of all variable names. * @return Set of all variable names.
*/ */
public String[] getVarKeyList() { 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 * verify is a var exists
* *
* @param name * @param name
* the key name of the var * the key name of the var
* @return true if that var exists * @return true if that var exists
*/ */
public boolean hasVar(String name) { public boolean hasVar(final String name) {
return variables.containsKey(name); return variables.containsKey(name);
} }
/** public boolean isEmpty() {
* Returns the quantity of vars this is holding return variables.isEmpty();
*
* @return the number of vars
*/
public int getSize() {
return variables.size();
} }
/** /**
* Remove a var from the list * Remove a var from the list
* *
* @param name * @param name
*/ */
public void removeVar(String name) { public void removeVar(final String name) {
try { try {
variables.remove(name); variables.remove(name);
} catch (Exception e) { } catch (final Exception e) {
} }
owner.flagAsChanged(); 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();
}
} }

View File

@ -9,18 +9,16 @@ import org.anjocaido.groupmanager.data.Group;
/** /**
* This container holds all Groups loaded from the relevant groupsFile. * This container holds all Groups loaded from the relevant groupsFile.
* *
* @author ElgarL * @author ElgarL
* *
*/ */
public class GroupsDataHolder { public class GroupsDataHolder {
private WorldDataHolder dataSource; private WorldDataHolder dataSource;
private Group defaultGroup = null; private Group defaultGroup = null;
private File groupsFile; private File groupsFile;
private boolean haveGroupsChanged = false; private boolean haveGroupsChanged = false;
private long timeStampGroups = 0; private long timeStampGroups = 0;
/** /**
* The actual groups holder * The actual groups holder
*/ */
@ -30,21 +28,9 @@ public class GroupsDataHolder {
* Constructor * Constructor
*/ */
protected GroupsDataHolder() { 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() { public WorldDataHolder getDataSource() {
return this.dataSource; return this.dataSource;
} }
@ -52,29 +38,39 @@ public class GroupsDataHolder {
* @return the defaultGroup * @return the defaultGroup
*/ */
public Group getDefaultGroup() { public Group getDefaultGroup() {
return defaultGroup; 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! * Note: Iteration over this object has to be synchronized!
* *
* @return the groups * @return the groups
*/ */
public Map<String, Group> getGroups() { public Map<String, Group> getGroups() {
return groups; 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 * Resets the Groups
*/ */
@ -82,55 +78,44 @@ public class GroupsDataHolder {
this.groups.clear(); this.groups.clear();
} }
/** public void setDataSource(final WorldDataHolder dataSource) {
* @return the groupsFile this.dataSource = dataSource;
*/ // push this data source to the users, so they pull the correct groups data.
public File getGroupsFile() { synchronized (groups) {
for (final Group group : groups.values())
return groupsFile; group.setDataSource(this.dataSource);
}
} }
/** /**
* @param groupsFile * @param defaultGroup
* the groupsFile to set * the defaultGroup to set
*/ */
public void setGroupsFile(File groupsFile) { public void setDefaultGroup(final Group defaultGroup) {
this.defaultGroup = defaultGroup;
this.groupsFile = groupsFile;
}
/**
* @return the haveGroupsChanged
*/
public boolean HaveGroupsChanged() {
return haveGroupsChanged;
} }
/** /**
* @param haveGroupsChanged * @param haveGroupsChanged
* the haveGroupsChanged to set * the haveGroupsChanged to set
*/ */
public void setGroupsChanged(boolean haveGroupsChanged) { public void setGroupsChanged(final boolean haveGroupsChanged) {
this.haveGroupsChanged = haveGroupsChanged; this.haveGroupsChanged = haveGroupsChanged;
} }
/** /**
* @return the timeStampGroups * @param groupsFile
* the groupsFile to set
*/ */
public long getTimeStampGroups() { public void setGroupsFile(final File groupsFile) {
this.groupsFile = groupsFile;
return timeStampGroups;
} }
/** /**
* @param timeStampGroups * @param timeStampGroups
* the timeStampGroups to set * the timeStampGroups to set
*/ */
public void setTimeStampGroups(long timeStampGroups) { public void setTimeStampGroups(final long timeStampGroups) {
this.timeStampGroups = timeStampGroups; this.timeStampGroups = timeStampGroups;
} }
} }

View File

@ -9,25 +9,24 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.data.User;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class OverloadedWorldHolder extends WorldDataHolder { public class OverloadedWorldHolder extends WorldDataHolder {
/** /**
* *
*/ */
protected final Map<String, User> overloadedUsers = Collections.synchronizedMap(new HashMap<String, User>()); protected final Map<String, User> overloadedUsers = Collections.synchronizedMap(new HashMap<String, User>());
/** /**
* *
* @param ph * @param ph
*/ */
public OverloadedWorldHolder(WorldDataHolder ph) { public OverloadedWorldHolder(final WorldDataHolder ph) {
super(ph.getName()); super(ph.getName());
this.setGroupsFile(ph.getGroupsFile()); this.setGroupsFile(ph.getGroupsFile());
this.setUsersFile(ph.getUsersFile()); 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 * @param theUser
*/ */
@Override @Override
public void addUser(User theUser) { public void addUser(User theUser) {
if (theUser.getDataSource() != this) { if (theUser.getDataSource() != this) {
theUser = theUser.clone(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<User> getUserList() {
final Collection<User> overloadedList = new ArrayList<User>();
synchronized (getUsers()) {
final Collection<User> 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 * @param userId
* @return true if removed/false if not found. * @return true if removed/false if not found.
*/ */
@Override @Override
public boolean removeUser(String userId) { public boolean removeUser(final String userId) {
// OVERLOADED CODE // OVERLOADED CODE
if (overloadedUsers.containsKey(userId.toLowerCase())) { if (overloadedUsers.containsKey(userId.toLowerCase())) {
overloadedUsers.remove(userId.toLowerCase()); overloadedUsers.remove(userId.toLowerCase());
@ -103,118 +186,22 @@ public class OverloadedWorldHolder extends WorldDataHolder {
return false; 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<User> getUserList() {
Collection<User> overloadedList = new ArrayList<User>();
synchronized (getUsers()) {
Collection<User> 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. * Gets the user in normal state. Surpassing the overload state.
* It doesn't affect permissions. But it enables plugins change the * It doesn't affect permissions. But it enables plugins change the
* actual user permissions even in overload mode. * actual user permissions even in overload mode.
* *
* @param userId * @param userId
* @return user object * @return user object
*/ */
public User surpassOverload(String userId) { public User surpassOverload(final String userId) {
if (!isOverloaded(userId)) { if (!isOverloaded(userId)) {
return getUser(userId); return getUser(userId);
} }
if (getUsers().containsKey(userId.toLowerCase())) { if (getUsers().containsKey(userId.toLowerCase())) {
return getUsers().get(userId.toLowerCase()); return getUsers().get(userId.toLowerCase());
} }
User newUser = createUser(userId); final User newUser = createUser(userId);
return newUser; return newUser;
} }
} }

View File

@ -9,17 +9,15 @@ import org.anjocaido.groupmanager.data.User;
/** /**
* This container holds all Users loaded from the relevant usersFile. * This container holds all Users loaded from the relevant usersFile.
* *
* @author ElgarL * @author ElgarL
* *
*/ */
public class UsersDataHolder { public class UsersDataHolder {
private WorldDataHolder dataSource; private WorldDataHolder dataSource;
private File usersFile; private File usersFile;
private boolean haveUsersChanged = false; private boolean haveUsersChanged = false;
private long timeStampUsers = 0; private long timeStampUsers = 0;
/** /**
* The actual groups holder * The actual groups holder
*/ */
@ -29,32 +27,40 @@ public class UsersDataHolder {
* Constructor * Constructor
*/ */
protected UsersDataHolder() { 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. * @return the timeStampUsers
synchronized (users) { */
for (User user : users.values()) public long getTimeStampUsers() {
user.setDataSource(this.dataSource); return timeStampUsers;
}
} }
/** /**
* Note: Iteration over this object has to be synchronized! * Note: Iteration over this object has to be synchronized!
* *
* @return the users * @return the users
*/ */
public Map<String, User> getUsers() { public Map<String, User> getUsers() {
return users; 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(); this.users.clear();
} }
/** public void setDataSource(final WorldDataHolder dataSource) {
* @return the usersFile this.dataSource = dataSource;
*/ // push this data source to the users, so they pull the correct groups data.
public File getUsersFile() { synchronized (users) {
for (final User user : users.values())
return usersFile; user.setDataSource(this.dataSource);
} }
/**
* @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;
} }
/** /**
* @param timeStampUsers * @param timeStampUsers
* the timeStampUsers to set * the timeStampUsers to set
*/ */
public void setTimeStampUsers(long timeStampUsers) { public void setTimeStampUsers(final long timeStampUsers) {
this.timeStampUsers = 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;
}
} }

View File

@ -46,7 +46,6 @@ import org.yaml.snakeyaml.reader.UnicodeReader;
* @author gabrielcouto, ElgarL * @author gabrielcouto, ElgarL
*/ */
public class WorldDataHolder { public class WorldDataHolder {
/** /**
* World name * World name
*/ */
@ -70,7 +69,6 @@ public class WorldDataHolder {
* @param worldName * @param worldName
*/ */
public WorldDataHolder(final String worldName) { public WorldDataHolder(final String worldName) {
name = worldName; name = worldName;
} }
@ -82,11 +80,9 @@ public class WorldDataHolder {
* @param users * @param users
*/ */
public WorldDataHolder(final String worldName, final GroupsDataHolder groups, final UsersDataHolder users) { public WorldDataHolder(final String worldName, final GroupsDataHolder groups, final UsersDataHolder users) {
this.name = worldName; this.name = worldName;
this.groups = groups; this.groups = groups;
this.users = users; this.users = users;
// this.defaultGroup = defaultGroup; // this.defaultGroup = defaultGroup;
} }
@ -101,16 +97,13 @@ public class WorldDataHolder {
* @throws IOException * @throws IOException
*/ */
public static WorldDataHolder load(final String worldName, final File groupsFile, final File usersFile) throws FileNotFoundException, IOException { public static WorldDataHolder load(final String worldName, final File groupsFile, final File usersFile) throws FileNotFoundException, IOException {
final WorldDataHolder ph = new WorldDataHolder(worldName); final WorldDataHolder ph = new WorldDataHolder(worldName);
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
if (groupsFile != null) if (groupsFile != null)
loadGroups(ph, groupsFile); loadGroups(ph, groupsFile);
if (usersFile != null) if (usersFile != null)
loadUsers(ph, usersFile); loadUsers(ph, usersFile);
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
return ph; return ph;
} }
@ -130,7 +123,6 @@ public class WorldDataHolder {
*/ */
@Deprecated @Deprecated
public static void reloadOldPlugins(final Server server) { public static void reloadOldPlugins(final Server server) {
// Only reload permissions // Only reload permissions
final PluginManager pm = server.getPluginManager(); final PluginManager pm = server.getPluginManager();
final Plugin[] plugins = pm.getPlugins(); final Plugin[] plugins = pm.getPlugins();
@ -151,46 +143,34 @@ public class WorldDataHolder {
* @param groupsFile * @param groupsFile
*/ */
public static void writeGroups(final WorldDataHolder ph, final File groupsFile) { public static void writeGroups(final WorldDataHolder ph, final File groupsFile) {
final Map<String, Object> root = new HashMap<String, Object>(); final Map<String, Object> root = new HashMap<String, Object>();
final Map<String, Object> groupsMap = new HashMap<String, Object>(); final Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap); root.put("groups", groupsMap);
synchronized (ph.getGroups()) { synchronized (ph.getGroups()) {
for (final String groupKey : ph.getGroups().keySet()) { for (final String groupKey : ph.getGroups().keySet()) {
final Group group = ph.getGroups().get(groupKey); final Group group = ph.getGroups().get(groupKey);
final Map<String, Object> aGroupMap = new HashMap<String, Object>(); final Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap); groupsMap.put(group.getName(), aGroupMap);
if (ph.getDefaultGroup() == null) { if (ph.getDefaultGroup() == null) {
GroupManager.logger.severe("There is no default group for world: " + ph.getName()); GroupManager.logger.severe("There is no default group for world: " + ph.getName());
} }
aGroupMap.put("default", group.equals(ph.getDefaultGroup())); aGroupMap.put("default", group.equals(ph.getDefaultGroup()));
final Map<String, Object> infoMap = new HashMap<String, Object>(); final Map<String, Object> infoMap = new HashMap<String, Object>();
aGroupMap.put("info", infoMap); aGroupMap.put("info", infoMap);
for (final String infoKey : group.getVariables().getVarKeyList()) { for (final String infoKey : group.getVariables().getVarKeyList()) {
infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
} }
aGroupMap.put("inheritance", group.getInherits()); aGroupMap.put("inheritance", group.getInherits());
aGroupMap.put("permissions", group.getPermissionList()); aGroupMap.put("permissions", group.getPermissionList());
} }
} }
if (!root.isEmpty()) { if (!root.isEmpty()) {
final DumperOptions opt = new DumperOptions(); final DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt); final Yaml yaml = new Yaml(opt);
try { try {
final OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(groupsFile), "UTF-8"); final OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(groupsFile), "UTF-8");
final String newLine = System.getProperty("line.separator"); final String newLine = System.getProperty("line.separator");
out.write("# Group inheritance" + newLine); out.write("# Group inheritance" + newLine);
out.write("#" + newLine); out.write("#" + newLine);
out.write("# Any inherited groups prefixed with a g: are global groups" + 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("#" + newLine);
out.write("# Local group inheritances define your promotion tree when using 'manpromote/mandemote'" + newLine); out.write("# Local group inheritances define your promotion tree when using 'manpromote/mandemote'" + newLine);
out.write(newLine); out.write(newLine);
yaml.dump(root, out); yaml.dump(root, out);
out.close(); out.close();
} catch (final UnsupportedEncodingException ex) { } catch (final UnsupportedEncodingException ex) {
@ -209,15 +188,12 @@ public class WorldDataHolder {
} catch (final IOException e) { } catch (final IOException e) {
} }
} }
// Update the LastModified time. // Update the LastModified time.
ph.setGroupsFile(groupsFile); ph.setGroupsFile(groupsFile);
ph.setTimeStampGroups(groupsFile.lastModified()); ph.setTimeStampGroups(groupsFile.lastModified());
ph.removeGroupsChangedFlag(); ph.removeGroupsChangedFlag();
if (GroupManager.isLoaded()) if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED); GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED);
/* /*
* FileWriter tx = null; try { tx = new FileWriter(groupsFile, false); * FileWriter tx = null; try { tx = new FileWriter(groupsFile, false);
* tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { } * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { }
@ -232,40 +208,31 @@ public class WorldDataHolder {
* @param usersFile * @param usersFile
*/ */
public static void writeUsers(final WorldDataHolder ph, final File usersFile) { public static void writeUsers(final WorldDataHolder ph, final File usersFile) {
final Map<String, Object> root = new HashMap<String, Object>(); final Map<String, Object> root = new HashMap<String, Object>();
final LinkedHashMap<String, Object> usersMap = new LinkedHashMap<String, Object>(); final LinkedHashMap<String, Object> usersMap = new LinkedHashMap<String, Object>();
root.put("users", usersMap); root.put("users", usersMap);
synchronized (ph.getUsers()) { synchronized (ph.getUsers()) {
// A sorted list of users. // A sorted list of users.
for (final String userKey : new TreeSet<String>(ph.getUsers().keySet())) { for (final String userKey : new TreeSet<String>(ph.getUsers().keySet())) {
final User user = ph.getUsers().get(userKey); final User user = ph.getUsers().get(userKey);
if ((user.getGroup() == null || user.getGroup().equals(ph.getDefaultGroup())) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) { if ((user.getGroup() == null || user.getGroup().equals(ph.getDefaultGroup())) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) {
continue; continue;
} }
final LinkedHashMap<String, Object> aUserMap = new LinkedHashMap<String, Object>(); final LinkedHashMap<String, Object> aUserMap = new LinkedHashMap<String, Object>();
usersMap.put(user.getUUID(), aUserMap); usersMap.put(user.getUUID(), aUserMap);
if (!user.getUUID().equalsIgnoreCase(user.getLastName())) { if (!user.getUUID().equalsIgnoreCase(user.getLastName())) {
aUserMap.put("lastname", user.getLastName()); aUserMap.put("lastname", user.getLastName());
} }
// GROUP NODE // GROUP NODE
if (user.getGroup() == null) { if (user.getGroup() == null) {
aUserMap.put("group", ph.getDefaultGroup().getName()); aUserMap.put("group", ph.getDefaultGroup().getName());
} else { } else {
aUserMap.put("group", user.getGroup().getName()); aUserMap.put("group", user.getGroup().getName());
} }
// SUBGROUPS NODE // SUBGROUPS NODE
aUserMap.put("subgroups", user.subGroupListStringCopy()); aUserMap.put("subgroups", user.subGroupListStringCopy());
// PERMISSIONS NODE // PERMISSIONS NODE
aUserMap.put("permissions", user.getPermissionList()); aUserMap.put("permissions", user.getPermissionList());
// USER INFO NODE - BETA // USER INFO NODE - BETA
if (user.getVariables().getSize() > 0) { if (user.getVariables().getSize() > 0) {
final Map<String, Object> infoMap = new HashMap<String, Object>(); final Map<String, Object> infoMap = new HashMap<String, Object>();
@ -275,10 +242,8 @@ public class WorldDataHolder {
} }
} }
// END USER INFO NODE - BETA // END USER INFO NODE - BETA
} }
} }
if (!root.isEmpty()) { if (!root.isEmpty()) {
final DumperOptions opt = new DumperOptions(); final DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
@ -292,15 +257,12 @@ public class WorldDataHolder {
} catch (final IOException e) { } catch (final IOException e) {
} }
} }
// Update the LastModified time. // Update the LastModified time.
ph.setUsersFile(usersFile); ph.setUsersFile(usersFile);
ph.setTimeStampUsers(usersFile.lastModified()); ph.setTimeStampUsers(usersFile.lastModified());
ph.removeUsersChangedFlag(); ph.removeUsersChangedFlag();
if (GroupManager.isLoaded()) if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED); GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED);
/* /*
* FileWriter tx = null; try { tx = new FileWriter(usersFile, false); * FileWriter tx = null; try { tx = new FileWriter(usersFile, false);
* tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { } * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { }
@ -319,12 +281,9 @@ public class WorldDataHolder {
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
protected static void loadGroups(final WorldDataHolder ph, final File groupsFile) throws FileNotFoundException, IOException { protected static void loadGroups(final WorldDataHolder ph, final File groupsFile) throws FileNotFoundException, IOException {
// READ GROUPS FILE // READ GROUPS FILE
final Yaml yamlGroups = new Yaml(new SafeConstructor()); final Yaml yamlGroups = new Yaml(new SafeConstructor());
Map<String, Object> groupsRootDataNode; Map<String, Object> groupsRootDataNode;
if (!groupsFile.exists()) { if (!groupsFile.exists()) {
throw new IllegalArgumentException("The file which should contain groups does not exist!\n" + groupsFile.getPath()); throw new IllegalArgumentException("The file which should contain groups does not exist!\n" + groupsFile.getPath());
} }
@ -339,12 +298,9 @@ public class WorldDataHolder {
} finally { } finally {
groupsInputStream.close(); groupsInputStream.close();
} }
// PROCESS GROUPS FILE // PROCESS GROUPS FILE
final Map<String, List<String>> inheritance = new HashMap<String, List<String>>(); final Map<String, List<String>> inheritance = new HashMap<String, List<String>>();
Map<String, Object> allGroupsNode = null; Map<String, Object> allGroupsNode = null;
/* /*
* Fetch all groups under the 'groups' entry. * Fetch all groups under the 'groups' entry.
*/ */
@ -353,20 +309,16 @@ public class WorldDataHolder {
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Your " + groupsFile.getPath() + " file is invalid. See console for details.", ex); throw new IllegalArgumentException("Your " + groupsFile.getPath() + " file is invalid. See console for details.", ex);
} }
if (allGroupsNode == null) { if (allGroupsNode == null) {
throw new IllegalArgumentException("You have no groups in " + groupsFile.getPath() + "."); throw new IllegalArgumentException("You have no groups in " + groupsFile.getPath() + ".");
} }
final Iterator<String> groupItr = allGroupsNode.keySet().iterator(); final Iterator<String> groupItr = allGroupsNode.keySet().iterator();
String groupKey; String groupKey;
Integer groupCount = 0; Integer groupCount = 0;
/* /*
* loop each group entry and process it's data. * loop each group entry and process it's data.
*/ */
while (groupItr.hasNext()) { while (groupItr.hasNext()) {
try { try {
groupCount++; groupCount++;
// Attempt to fetch the next group name. // Attempt to fetch the next group name.
@ -374,36 +326,29 @@ public class WorldDataHolder {
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid group name for group entry (" + groupCount + ") in file: " + groupsFile.getPath(), ex); throw new IllegalArgumentException("Invalid group name for group entry (" + groupCount + ") in file: " + groupsFile.getPath(), ex);
} }
/* /*
* Fetch this groups child nodes * Fetch this groups child nodes
*/ */
Map<String, Object> thisGroupNode = null; Map<String, Object> thisGroupNode = null;
try { try {
thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey); thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey);
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid child nodes for group '" + groupKey + "' in file: " + groupsFile.getPath(), 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. * Create a new group with this name in the assigned data source.
*/ */
final Group thisGrp = ph.createGroup(groupKey); final Group thisGrp = ph.createGroup(groupKey);
if (thisGrp == null) { if (thisGrp == null) {
throw new IllegalArgumentException("I think this Group was declared more than once: " + groupKey + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("I think this Group was declared more than once: " + groupKey + " in file: " + groupsFile.getPath());
} }
// DEFAULT NODE // DEFAULT NODE
Object nodeData = null; Object nodeData = null;
try { try {
nodeData = thisGroupNode.get("default"); nodeData = thisGroupNode.get("default");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'permissions' for group: " + groupKey + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Bad format found in 'permissions' for group: " + groupKey + " in file: " + groupsFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* If no 'default' node is found do nothing. * If no 'default' node is found do nothing.
@ -419,16 +364,13 @@ public class WorldDataHolder {
} }
ph.setDefaultGroup(thisGrp); ph.setDefaultGroup(thisGrp);
} }
// PERMISSIONS NODE // PERMISSIONS NODE
nodeData = null; nodeData = null;
try { try {
nodeData = thisGroupNode.get("permissions"); nodeData = thisGroupNode.get("permissions");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'permissions' for '" + groupKey + "' in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Bad format found in 'permissions' for '" + groupKey + "' in file: " + groupsFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* If no permissions node is found, or it's empty do nothing. * If no permissions node is found, or it's empty do nothing.
@ -449,7 +391,6 @@ public class WorldDataHolder {
*/ */
if (!o.toString().isEmpty()) if (!o.toString().isEmpty())
thisGrp.addPermission(o.toString()); thisGrp.addPermission(o.toString());
} catch (final NullPointerException ex) { } catch (final NullPointerException ex) {
// Ignore this entry as it's null. It can be // Ignore this entry as it's null. It can be
// safely dropped // safely dropped
@ -458,14 +399,12 @@ public class WorldDataHolder {
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid formatting found in 'permissions' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); throw new IllegalArgumentException("Invalid formatting found in 'permissions' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
} }
} else if (nodeData instanceof String) { } else if (nodeData instanceof String) {
/* /*
* Only add this permission if it's not empty. * Only add this permission if it's not empty.
*/ */
if (!nodeData.toString().isEmpty()) if (!nodeData.toString().isEmpty())
thisGrp.addPermission((String) nodeData); thisGrp.addPermission((String) nodeData);
} else { } else {
throw new IllegalArgumentException("Unknown type of 'permissions' node(Should be String or List<String>) for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Unknown type of 'permissions' node(Should be String or List<String>) for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath());
} }
@ -475,16 +414,13 @@ public class WorldDataHolder {
*/ */
thisGrp.sortPermissions(); thisGrp.sortPermissions();
} }
// INFO NODE // INFO NODE
nodeData = null; nodeData = null;
try { try {
nodeData = thisGroupNode.get("info"); nodeData = thisGroupNode.get("info");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'info' section for group: " + groupKey + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Bad format found in 'info' section for group: " + groupKey + " in file: " + groupsFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* No info section was found, so leave all variables as * 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("The group '" + thisGrp.getName() + "' has no 'info' section!");
GroupManager.logger.warning("Using default values: " + groupsFile.getPath()); GroupManager.logger.warning("Using default values: " + groupsFile.getPath());
} else if (nodeData instanceof Map) { } else if (nodeData instanceof Map) {
try { try {
if (nodeData != null) { if (nodeData != null) {
@ -501,19 +436,15 @@ public class WorldDataHolder {
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid formatting found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); throw new IllegalArgumentException("Invalid formatting found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
} }
} else } else
throw new IllegalArgumentException("Unknown entry found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Unknown entry found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath());
// INHERITANCE NODE // INHERITANCE NODE
nodeData = null; nodeData = null;
try { try {
nodeData = thisGroupNode.get("inheritance"); nodeData = thisGroupNode.get("inheritance");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'inheritance' section for group: " + groupKey + " in file: " + groupsFile.getPath()); 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 || nodeData instanceof List) {
if (nodeData == null) { if (nodeData == null) {
/* /*
@ -521,7 +452,6 @@ public class WorldDataHolder {
* nothing. * nothing.
*/ */
} else if (nodeData instanceof List) { } else if (nodeData instanceof List) {
try { try {
for (final String grp : (List<String>) nodeData) { for (final String grp : (List<String>) nodeData) {
if (inheritance.get(groupKey) == null) { if (inheritance.get(groupKey) == null) {
@ -529,23 +459,17 @@ public class WorldDataHolder {
} }
inheritance.get(groupKey).add(grp); inheritance.get(groupKey).add(grp);
} }
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid formatting found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex); throw new IllegalArgumentException("Invalid formatting found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
} }
} }
} else } else
throw new IllegalArgumentException("Unknown entry found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath()); throw new IllegalArgumentException("Unknown entry found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath());
// END GROUP // END GROUP
} }
if (ph.getDefaultGroup() == null) { if (ph.getDefaultGroup() == null) {
throw new IllegalArgumentException("There was no Default Group declared in file: " + groupsFile.getPath()); throw new IllegalArgumentException("There was no Default Group declared in file: " + groupsFile.getPath());
} }
/* /*
* Build the inheritance map and recored any errors * Build the inheritance map and recored any errors
*/ */
@ -563,12 +487,10 @@ public class WorldDataHolder {
} }
} }
} }
ph.removeGroupsChangedFlag(); ph.removeGroupsChangedFlag();
// Update the LastModified time. // Update the LastModified time.
ph.setGroupsFile(groupsFile); ph.setGroupsFile(groupsFile);
ph.setTimeStampGroups(groupsFile.lastModified()); ph.setTimeStampGroups(groupsFile.lastModified());
// return ph; // return ph;
} }
@ -583,7 +505,6 @@ public class WorldDataHolder {
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
protected static void loadUsers(final WorldDataHolder ph, final File usersFile) throws FileNotFoundException, IOException { protected static void loadUsers(final WorldDataHolder ph, final File usersFile) throws FileNotFoundException, IOException {
// READ USERS FILE // READ USERS FILE
final Yaml yamlUsers = new Yaml(new SafeConstructor()); final Yaml yamlUsers = new Yaml(new SafeConstructor());
Map<String, Object> usersRootDataNode; Map<String, Object> usersRootDataNode;
@ -601,11 +522,8 @@ public class WorldDataHolder {
} finally { } finally {
usersInputStream.close(); usersInputStream.close();
} }
// PROCESS USERS FILE // PROCESS USERS FILE
Map<String, Object> allUsersNode = null; Map<String, Object> allUsersNode = null;
/* /*
* Fetch all child nodes under the 'users' entry. * Fetch all child nodes under the 'users' entry.
*/ */
@ -614,16 +532,12 @@ public class WorldDataHolder {
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Your " + usersFile.getPath() + " file is invalid. See console for details.", ex); throw new IllegalArgumentException("Your " + usersFile.getPath() + " file is invalid. See console for details.", ex);
} }
// Load users if the file is NOT empty // Load users if the file is NOT empty
if (allUsersNode != null) { if (allUsersNode != null) {
final Iterator<String> usersItr = allUsersNode.keySet().iterator(); final Iterator<String> usersItr = allUsersNode.keySet().iterator();
String usersKey; String usersKey;
Object node; Object node;
Integer userCount = 0; Integer userCount = 0;
while (usersItr.hasNext()) { while (usersItr.hasNext()) {
try { try {
userCount++; userCount++;
@ -633,49 +547,36 @@ public class WorldDataHolder {
usersKey = Integer.toString((Integer) node); usersKey = Integer.toString((Integer) node);
else else
usersKey = node.toString(); usersKey = node.toString();
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Invalid node type for user entry (" + userCount + ") in file: " + usersFile.getPath(), ex); throw new IllegalArgumentException("Invalid node type for user entry (" + userCount + ") in file: " + usersFile.getPath(), ex);
} }
Map<String, Object> thisUserNode = null; Map<String, Object> thisUserNode = null;
try { try {
thisUserNode = (Map<String, Object>) allUsersNode.get(node); thisUserNode = (Map<String, Object>) allUsersNode.get(node);
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found for user: " + usersKey + " in file: " + usersFile.getPath());
} }
final User thisUser = ph.createUser(usersKey); final User thisUser = ph.createUser(usersKey);
if (thisUser == null) { if (thisUser == null) {
throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey + " in file: " + usersFile.getPath());
} }
// LASTNAME NODES // LASTNAME NODES
Object nodeData = null; Object nodeData = null;
try { try {
nodeData = thisUserNode.get("lastname"); nodeData = thisUserNode.get("lastname");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath());
} }
if ((nodeData != null) && (nodeData instanceof String)) { if ((nodeData != null) && (nodeData instanceof String)) {
thisUser.setLastName((String) nodeData); thisUser.setLastName((String) nodeData);
} }
// USER PERMISSIONS NODES // USER PERMISSIONS NODES
nodeData = null; nodeData = null;
try { try {
nodeData = thisUserNode.get("permissions"); nodeData = thisUserNode.get("permissions");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'permissions' for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found in 'permissions' for user: " + usersKey + " in file: " + usersFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* If no permissions node is found, or it's empty do * If no permissions node is found, or it's empty do
@ -693,30 +594,25 @@ public class WorldDataHolder {
} }
} }
} else if (nodeData instanceof String) { } else if (nodeData instanceof String) {
/* /*
* Only add this permission if it's not empty * Only add this permission if it's not empty
*/ */
if (!nodeData.toString().isEmpty()) { if (!nodeData.toString().isEmpty()) {
thisUser.addPermission(nodeData.toString()); thisUser.addPermission(nodeData.toString());
} }
} }
} catch (final NullPointerException e) { } catch (final NullPointerException e) {
// Ignore this entry as it's null. // Ignore this entry as it's null.
} }
thisUser.sortPermissions(); thisUser.sortPermissions();
} }
// SUBGROUPS NODES // SUBGROUPS NODES
nodeData = null; nodeData = null;
try { try {
nodeData = thisUserNode.get("subgroups"); nodeData = thisUserNode.get("subgroups");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* If no subgroups node is found, or it's empty do nothing. * 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()); GroupManager.logger.warning("Subgroup '" + nodeData.toString() + "' not found for user: " + thisUser.getLastName() + ". Ignoring entry in file: " + usersFile.getPath());
} }
} }
// USER INFO NODE // USER INFO NODE
nodeData = null; nodeData = null;
try { try {
nodeData = thisUserNode.get("info"); nodeData = thisUserNode.get("info");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'info' section for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found in 'info' section for user: " + usersKey + " in file: " + usersFile.getPath());
} }
if (nodeData == null) { if (nodeData == null) {
/* /*
* If no info node is found, or it's empty do nothing. * If no info node is found, or it's empty do nothing.
*/ */
} else if (nodeData instanceof Map) { } else if (nodeData instanceof Map) {
thisUser.setVariables((Map<String, Object>) nodeData); thisUser.setVariables((Map<String, Object>) nodeData);
} else } else
throw new IllegalArgumentException("Unknown entry found in 'info' section for user: " + thisUser.getLastName() + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Unknown entry found in 'info' section for user: " + thisUser.getLastName() + " in file: " + usersFile.getPath());
// END INFO NODE // END INFO NODE
// PRIMARY GROUP // PRIMARY GROUP
nodeData = null; nodeData = null;
try { try {
nodeData = thisUserNode.get("group"); nodeData = thisUserNode.get("group");
} catch (final Exception ex) { } catch (final Exception ex) {
throw new IllegalArgumentException("Bad format found in 'group' section for user: " + usersKey + " in file: " + usersFile.getPath()); throw new IllegalArgumentException("Bad format found in 'group' section for user: " + usersKey + " in file: " + usersFile.getPath());
} }
if (nodeData != null) { if (nodeData != null) {
Group hisGroup = ph.getGroup(nodeData.toString()); Group hisGroup = ph.getGroup(nodeData.toString());
if (hisGroup == null) { if (hisGroup == null) {
@ -786,7 +674,6 @@ public class WorldDataHolder {
} }
} }
} }
ph.removeUsersChangedFlag(); ph.removeUsersChangedFlag();
// Update the LastModified time. // Update the LastModified time.
ph.setUsersFile(usersFile); ph.setUsersFile(usersFile);
@ -799,13 +686,11 @@ public class WorldDataHolder {
* @param groupToAdd * @param groupToAdd
*/ */
public void addGroup(Group groupToAdd) { public void addGroup(Group groupToAdd) {
if (groupToAdd.getName().toLowerCase().startsWith("g:")) { if (groupToAdd.getName().toLowerCase().startsWith("g:")) {
GroupManager.getGlobalGroups().addGroup(groupToAdd); GroupManager.getGlobalGroups().addGroup(groupToAdd);
GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED); GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
return; return;
} }
if (groupToAdd.getDataSource() != this) { if (groupToAdd.getDataSource() != this) {
groupToAdd = groupToAdd.clone(this); groupToAdd = groupToAdd.clone(this);
} }
@ -823,7 +708,6 @@ public class WorldDataHolder {
* the user you want to add to the permission list * the user you want to add to the permission list
*/ */
public void addUser(User theUser) { public void addUser(User theUser) {
if (theUser.getDataSource() != this) { if (theUser.getDataSource() != this) {
theUser = theUser.clone(this); theUser = theUser.clone(this);
} }
@ -848,16 +732,13 @@ public class WorldDataHolder {
* @return null if group already exists. or new Group * @return null if group already exists. or new Group
*/ */
public Group createGroup(final String groupName) { public Group createGroup(final String groupName) {
if (groupName.toLowerCase().startsWith("g:")) { if (groupName.toLowerCase().startsWith("g:")) {
final Group newGroup = new Group(groupName); final Group newGroup = new Group(groupName);
return GroupManager.getGlobalGroups().newGroup(newGroup); return GroupManager.getGlobalGroups().newGroup(newGroup);
} }
if (getGroups().containsKey(groupName.toLowerCase())) { if (getGroups().containsKey(groupName.toLowerCase())) {
return null; return null;
} }
final Group newGroup = new Group(this, groupName); final Group newGroup = new Group(this, groupName);
addGroup(newGroup); addGroup(newGroup);
setGroupsChanged(true); setGroupsChanged(true);
@ -872,7 +753,6 @@ public class WorldDataHolder {
* @return null if user already exists. or new User * @return null if user already exists. or new User
*/ */
public User createUser(final String userId) { public User createUser(final String userId) {
if (getUsers().containsKey(userId.toLowerCase())) { if (getUsers().containsKey(userId.toLowerCase())) {
return null; return null;
} }
@ -889,7 +769,6 @@ public class WorldDataHolder {
* @return the default group * @return the default group
*/ */
public Group getDefaultGroup() { public Group getDefaultGroup() {
return groups.getDefaultGroup(); return groups.getDefaultGroup();
} }
@ -911,7 +790,6 @@ public class WorldDataHolder {
* @return a collection of the groups * @return a collection of the groups
*/ */
public Collection<Group> getGroupList() { public Collection<Group> getGroupList() {
synchronized (getGroups()) { synchronized (getGroups()) {
return new ArrayList<Group>(getGroups().values()); return new ArrayList<Group>(getGroups().values());
} }
@ -923,7 +801,6 @@ public class WorldDataHolder {
* @return the groups * @return the groups
*/ */
public Map<String, Group> getGroups() { public Map<String, Group> getGroups() {
return groups.getGroups(); return groups.getGroups();
} }
@ -931,7 +808,6 @@ public class WorldDataHolder {
* @return the groupsFile * @return the groupsFile
*/ */
public File getGroupsFile() { public File getGroupsFile() {
return groups.getGroupsFile(); return groups.getGroupsFile();
} }
@ -939,7 +815,6 @@ public class WorldDataHolder {
* @return the groups * @return the groups
*/ */
public GroupsDataHolder getGroupsObject() { public GroupsDataHolder getGroupsObject() {
return groups; return groups;
} }
@ -947,7 +822,6 @@ public class WorldDataHolder {
* @return the name * @return the name
*/ */
public String getName() { public String getName() {
return name; return name;
} }
@ -955,7 +829,6 @@ public class WorldDataHolder {
* @return the permissionsHandler * @return the permissionsHandler
*/ */
public AnjoPermissionsHandler getPermissionsHandler() { public AnjoPermissionsHandler getPermissionsHandler() {
if (permissionsHandler == null) { if (permissionsHandler == null) {
permissionsHandler = new AnjoPermissionsHandler(this); permissionsHandler = new AnjoPermissionsHandler(this);
} }
@ -966,7 +839,6 @@ public class WorldDataHolder {
* @return the timeStampGroups * @return the timeStampGroups
*/ */
public long getTimeStampGroups() { public long getTimeStampGroups() {
return groups.getTimeStampGroups(); return groups.getTimeStampGroups();
} }
@ -974,7 +846,6 @@ public class WorldDataHolder {
* @return the timeStampUsers * @return the timeStampUsers
*/ */
public long getTimeStampUsers() { public long getTimeStampUsers() {
return users.getTimeStampUsers(); return users.getTimeStampUsers();
} }
@ -987,27 +858,20 @@ public class WorldDataHolder {
* @return class that manage that user permission * @return class that manage that user permission
*/ */
public User getUser(final String userId) { public User getUser(final String userId) {
if (getUsers().containsKey(userId.toLowerCase())) { if (getUsers().containsKey(userId.toLowerCase())) {
return getUsers().get(userId.toLowerCase()); return getUsers().get(userId.toLowerCase());
} }
// Legacy name matching // Legacy name matching
if (userId.length() < 36) { if (userId.length() < 36) {
// Search for a LastName match // Search for a LastName match
for (final User user : getUserList()) { for (final User user : getUserList()) {
if (user.getLastName().equalsIgnoreCase(userId)) { if (user.getLastName().equalsIgnoreCase(userId)) {
return user; return user;
} }
} }
} }
// No user account found so create a new one. // No user account found so create a new one.
final User newUser = createUser(userId); final User newUser = createUser(userId);
return newUser; return newUser;
} }
@ -1022,38 +886,26 @@ public class WorldDataHolder {
* @return the user object for this player. * @return the user object for this player.
*/ */
public User getUser(final String uUID, final String currentName) { public User getUser(final String uUID, final String currentName) {
// Check for a UUID account // Check for a UUID account
User user = getUsers().get(uUID.toLowerCase()); User user = getUsers().get(uUID.toLowerCase());
if (user != null) { if (user != null) {
user.setLastName(currentName); user.setLastName(currentName);
return user; return user;
} }
// Search for a LastName match // Search for a LastName match
for (final User usr : getUserList()) { for (final User usr : getUserList()) {
if (usr.getLastName().equalsIgnoreCase(currentName) && usr.getUUID().equalsIgnoreCase(usr.getLastName())) { if (usr.getLastName().equalsIgnoreCase(currentName) && usr.getUUID().equalsIgnoreCase(usr.getLastName())) {
// Clone this user so we can set it's uUID // Clone this user so we can set it's uUID
user = usr.clone(uUID, currentName); user = usr.clone(uUID, currentName);
// Delete it and replace with the new clone. // Delete it and replace with the new clone.
this.removeUser(usr.getUUID()); this.removeUser(usr.getUUID());
this.addUser(user); this.addUser(user);
return getUsers().get(uUID.toLowerCase()); return getUsers().get(uUID.toLowerCase());
} }
} }
// No user account found so create a new one. // No user account found so create a new one.
final User newUser = createUser(uUID); final User newUser = createUser(uUID);
newUser.setLastName(currentName); newUser.setLastName(currentName);
return newUser; return newUser;
} }
@ -1062,7 +914,6 @@ public class WorldDataHolder {
* @return a collection of the users * @return a collection of the users
*/ */
public Collection<User> getUserList() { public Collection<User> getUserList() {
synchronized (getUsers()) { synchronized (getUsers()) {
return new ArrayList<User>(getUsers().values()); return new ArrayList<User>(getUsers().values());
} }
@ -1074,7 +925,6 @@ public class WorldDataHolder {
* @return the users * @return the users
*/ */
public Map<String, User> getUsers() { public Map<String, User> getUsers() {
return users.getUsers(); return users.getUsers();
} }
@ -1082,7 +932,6 @@ public class WorldDataHolder {
* @return the usersFile * @return the usersFile
*/ */
public File getUsersFile() { public File getUsersFile() {
return users.getUsersFile(); return users.getUsersFile();
} }
@ -1090,7 +939,6 @@ public class WorldDataHolder {
* @return the users * @return the users
*/ */
public UsersDataHolder getUsersObject() { public UsersDataHolder getUsersObject() {
return users; return users;
} }
@ -1113,7 +961,6 @@ public class WorldDataHolder {
* @return true if any group data has changed. * @return true if any group data has changed.
*/ */
public boolean haveGroupsChanged() { public boolean haveGroupsChanged() {
if (groups.HaveGroupsChanged()) { if (groups.HaveGroupsChanged()) {
return true; return true;
} }
@ -1132,7 +979,6 @@ public class WorldDataHolder {
* @return true if any user data has changed * @return true if any user data has changed
*/ */
public boolean haveUsersChanged() { public boolean haveUsersChanged() {
if (users.HaveUsersChanged()) { if (users.HaveUsersChanged()) {
return true; return true;
} }
@ -1152,12 +998,10 @@ public class WorldDataHolder {
* @return true if we have data for this player. * @return true if we have data for this player.
*/ */
public boolean isUserDeclared(final String userId) { public boolean isUserDeclared(final String userId) {
return getUsers().containsKey(userId.toLowerCase()); return getUsers().containsKey(userId.toLowerCase());
} }
public void loadGroups(final File groupsFile) { public void loadGroups(final File groupsFile) {
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
try { try {
setGroupsFile(groupsFile); setGroupsFile(groupsFile);
@ -1169,12 +1013,10 @@ public class WorldDataHolder {
e.printStackTrace(); e.printStackTrace();
throw new IllegalArgumentException("Error accessing the groups file!\n" + groupsFile.getPath()); throw new IllegalArgumentException("Error accessing the groups file!\n" + groupsFile.getPath());
} }
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
} }
public void loadUsers(final File usersFile) { public void loadUsers(final File usersFile) {
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
try { try {
setUsersFile(usersFile); setUsersFile(usersFile);
@ -1186,7 +1028,6 @@ public class WorldDataHolder {
e.printStackTrace(); e.printStackTrace();
throw new IllegalArgumentException("Error accessing the users file!\n" + usersFile.getPath()); throw new IllegalArgumentException("Error accessing the users file!\n" + usersFile.getPath());
} }
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
} }
@ -1194,7 +1035,6 @@ public class WorldDataHolder {
* reads the file again * reads the file again
*/ */
public void reload() { public void reload() {
try { try {
reloadGroups(); reloadGroups();
reloadUsers(); reloadUsers();
@ -1207,12 +1047,10 @@ public class WorldDataHolder {
* Refresh Group data from file * Refresh Group data from file
*/ */
public void reloadGroups() { public void reloadGroups() {
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
try { try {
// temporary holder in case the load fails. // temporary holder in case the load fails.
WorldDataHolder ph = new WorldDataHolder(this.getName()); WorldDataHolder ph = new WorldDataHolder(this.getName());
loadGroups(ph, getGroupsFile()); loadGroups(ph, getGroupsFile());
// transfer new data // transfer new data
resetGroups(); resetGroups();
@ -1222,7 +1060,6 @@ public class WorldDataHolder {
this.setDefaultGroup(getGroup(ph.getDefaultGroup().getName())); this.setDefaultGroup(getGroup(ph.getDefaultGroup().getName()));
this.removeGroupsChangedFlag(); this.removeGroupsChangedFlag();
this.setTimeStampGroups(getGroupsFile().lastModified()); this.setTimeStampGroups(getGroupsFile().lastModified());
ph = null; ph = null;
} catch (final Exception ex) { } catch (final Exception ex) {
Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex); Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex);
@ -1235,7 +1072,6 @@ public class WorldDataHolder {
* Refresh Users data from file * Refresh Users data from file
*/ */
public void reloadUsers() { public void reloadUsers() {
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
try { try {
// temporary holder in case the load fails. // temporary holder in case the load fails.
@ -1254,7 +1090,6 @@ public class WorldDataHolder {
} }
this.removeUsersChangedFlag(); this.removeUsersChangedFlag();
this.setTimeStampUsers(getUsersFile().lastModified()); this.setTimeStampUsers(getUsersFile().lastModified());
ph = null; ph = null;
} catch (final Exception ex) { } catch (final Exception ex) {
Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex); Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex);
@ -1271,11 +1106,9 @@ public class WorldDataHolder {
* non-existant * non-existant
*/ */
public boolean removeGroup(final String groupName) { public boolean removeGroup(final String groupName) {
if (groupName.toLowerCase().startsWith("g:")) { if (groupName.toLowerCase().startsWith("g:")) {
return GroupManager.getGlobalGroups().removeGroup(groupName); return GroupManager.getGlobalGroups().removeGroup(groupName);
} }
if (getDefaultGroup() != null && groupName.equalsIgnoreCase(getDefaultGroup().getName())) { if (getDefaultGroup() != null && groupName.equalsIgnoreCase(getDefaultGroup().getName())) {
return false; return false;
} }
@ -1287,14 +1120,12 @@ public class WorldDataHolder {
return true; return true;
} }
return false; return false;
} }
/** /**
* *
*/ */
public void removeGroupsChangedFlag() { public void removeGroupsChangedFlag() {
setGroupsChanged(false); setGroupsChanged(false);
synchronized (getGroups()) { synchronized (getGroups()) {
for (final Group g : getGroups().values()) { for (final Group g : getGroups().values()) {
@ -1311,7 +1142,6 @@ public class WorldDataHolder {
* @return true if it had something to remove * @return true if it had something to remove
*/ */
public boolean removeUser(final String userId) { public boolean removeUser(final String userId) {
if (getUsers().containsKey(userId.toLowerCase())) { if (getUsers().containsKey(userId.toLowerCase())) {
getUsers().remove(userId.toLowerCase()); getUsers().remove(userId.toLowerCase());
setUsersChanged(true); setUsersChanged(true);
@ -1326,7 +1156,6 @@ public class WorldDataHolder {
* *
*/ */
public void removeUsersChangedFlag() { public void removeUsersChangedFlag() {
setUsersChanged(false); setUsersChanged(false);
synchronized (getUsers()) { synchronized (getUsers()) {
for (final User u : getUsers().values()) { for (final User u : getUsers().values()) {
@ -1339,7 +1168,6 @@ public class WorldDataHolder {
* Resets Groups. * Resets Groups.
*/ */
public void resetGroups() { public void resetGroups() {
// setDefaultGroup(null); // setDefaultGroup(null);
groups.resetGroups(); groups.resetGroups();
} }
@ -1348,7 +1176,6 @@ public class WorldDataHolder {
* Resets Users * Resets Users
*/ */
public void resetUsers() { public void resetUsers() {
users.resetUsers(); users.resetUsers();
} }
@ -1359,7 +1186,6 @@ public class WorldDataHolder {
* the group you want make default. * the group you want make default.
*/ */
public void setDefaultGroup(final Group group) { public void setDefaultGroup(final Group group) {
if (!getGroups().containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) { if (!getGroups().containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) {
addGroup(group); addGroup(group);
} }
@ -1374,7 +1200,6 @@ public class WorldDataHolder {
* the haveGroupsChanged to set * the haveGroupsChanged to set
*/ */
public void setGroupsChanged(final boolean setGroupsChanged) { public void setGroupsChanged(final boolean setGroupsChanged) {
groups.setGroupsChanged(setGroupsChanged); groups.setGroupsChanged(setGroupsChanged);
} }
@ -1383,7 +1208,6 @@ public class WorldDataHolder {
* the groupsFile to set * the groupsFile to set
*/ */
public void setGroupsFile(final File file) { public void setGroupsFile(final File file) {
groups.setGroupsFile(file); groups.setGroupsFile(file);
} }
@ -1392,12 +1216,10 @@ public class WorldDataHolder {
* the GroupsDataHolder to set * the GroupsDataHolder to set
*/ */
public void setGroupsObject(final GroupsDataHolder groupsDataHolder) { public void setGroupsObject(final GroupsDataHolder groupsDataHolder) {
groups = groupsDataHolder; groups = groupsDataHolder;
} }
public void setTimeStamps() { public void setTimeStamps() {
if (getGroupsFile() != null) if (getGroupsFile() != null)
setTimeStampGroups(getGroupsFile().lastModified()); setTimeStampGroups(getGroupsFile().lastModified());
if (getUsersFile() != null) if (getUsersFile() != null)
@ -1409,7 +1231,6 @@ public class WorldDataHolder {
* the haveUsersChanged to set * the haveUsersChanged to set
*/ */
public void setUsersChanged(final boolean haveUsersChanged) { public void setUsersChanged(final boolean haveUsersChanged) {
users.setUsersChanged(haveUsersChanged); users.setUsersChanged(haveUsersChanged);
} }
@ -1418,7 +1239,6 @@ public class WorldDataHolder {
* the usersFile to set * the usersFile to set
*/ */
public void setUsersFile(final File file) { public void setUsersFile(final File file) {
users.setUsersFile(file); users.setUsersFile(file);
} }
@ -1427,7 +1247,6 @@ public class WorldDataHolder {
* the UsersDataHolder to set * the UsersDataHolder to set
*/ */
public void setUsersObject(final UsersDataHolder usersDataHolder) { public void setUsersObject(final UsersDataHolder usersDataHolder) {
users = usersDataHolder; users = usersDataHolder;
} }
@ -1437,7 +1256,6 @@ public class WorldDataHolder {
* This should be called whenever a set of world data is fetched. * This should be called whenever a set of world data is fetched.
*/ */
public void updateDataSource() { public void updateDataSource() {
this.groups.setDataSource(this); this.groups.setDataSource(this);
this.users.setDataSource(this); this.users.setDataSource(this);
} }
@ -1447,7 +1265,6 @@ public class WorldDataHolder {
* the timeStampGroups to set * the timeStampGroups to set
*/ */
protected void setTimeStampGroups(final long timeStampGroups) { protected void setTimeStampGroups(final long timeStampGroups) {
groups.setTimeStampGroups(timeStampGroups); groups.setTimeStampGroups(timeStampGroups);
} }
@ -1456,8 +1273,6 @@ public class WorldDataHolder {
* the timeStampUsers to set * the timeStampUsers to set
*/ */
protected void setTimeStampUsers(final long timeStampUsers) { protected void setTimeStampUsers(final long timeStampUsers) {
users.setTimeStampUsers(timeStampUsers); users.setTimeStampUsers(timeStampUsers);
} }
} }

View File

@ -10,71 +10,51 @@ import org.bukkit.event.HandlerList;
* *
*/ */
public class GMGroupEvent extends Event { public class GMGroupEvent extends Event {
/**
*
*/
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
protected Group group; protected Group group;
protected String groupName; protected String groupName;
////////////////////////////// //////////////////////////////
protected Action action; protected Action action;
public GMGroupEvent(final Group group, final Action action) { public GMGroupEvent(final Group group, final Action action) {
super(); super();
this.group = group; this.group = group;
this.action = action; this.action = action;
this.groupName = group.getName(); this.groupName = group.getName();
} }
public GMGroupEvent(final String groupName, final Action action) { public GMGroupEvent(final String groupName, final Action action) {
super(); super();
this.groupName = groupName; this.groupName = groupName;
this.action = action; this.action = action;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public Action getAction() { public Action getAction() {
return this.action; return this.action;
} }
public Group getGroup() { public Group getGroup() {
return group; return group;
} }
public String getGroupName() { public String getGroupName() {
return groupName; return groupName;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public void schedule(final GMGroupEvent event) { public void schedule(final GMGroupEvent event) {
synchronized (GroupManager.getGMEventHandler().getServer()) { synchronized (GroupManager.getGMEventHandler().getServer()) {
if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() { if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() {
@Override @Override
public void run() { public void run() {
GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event); GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event);
} }
}, 1) == -1) }, 1) == -1)

View File

@ -6,61 +6,47 @@ import org.bukkit.event.HandlerList;
/** /**
* @author ElgarL * @author ElgarL
* *
*/ */
public class GMSystemEvent extends Event { public class GMSystemEvent extends Event {
/**
*
*/
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected Action action; protected Action action;
public GMSystemEvent(Action action) { public GMSystemEvent(final Action action) {
super(); super();
this.action = action; this.action = action;
} }
public Action getAction() { //////////////////////////////
public static HandlerList getHandlerList() {
return handlers;
}
public Action getAction() {
return this.action; 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 { public enum Action {
RELOADED, RELOADED,
SAVED, SAVED,
DEFAULT_GROUP_CHANGED, DEFAULT_GROUP_CHANGED,
VALIDATE_TOGGLE, 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.");
}
}
} }

View File

@ -7,66 +7,62 @@ import org.bukkit.event.HandlerList;
/** /**
* @author ElgarL * @author ElgarL
* *
*/ */
public class GMUserEvent extends Event { public class GMUserEvent extends Event {
/**
*
*/
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected User user; protected User user;
protected String userName; protected String userName;
//////////////////////////////
protected Action action; protected Action action;
public GMUserEvent(User user, Action action) { public GMUserEvent(final String userName, final Action action) {
super(); super();
this.userName = userName;
this.action = action;
}
public GMUserEvent(final User user, final Action action) {
super();
this.user = user; this.user = user;
this.action = action; this.action = action;
this.userName = user.getLastName(); this.userName = user.getLastName();
} }
public GMUserEvent(String userName, Action action) { public static HandlerList getHandlerList() {
return handlers;
super();
this.userName = userName;
this.action = action;
} }
public Action getAction() { public Action getAction() {
return this.action; return this.action;
} }
public User getUser() { @Override
public HandlerList getHandlers() {
return handlers;
}
public User getUser() {
return user; return user;
} }
public String getUserName() { public String getUserName() {
return userName; 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 { public enum Action {
USER_PERMISSIONS_CHANGED, USER_PERMISSIONS_CHANGED,
USER_INHERITANCE_CHANGED, USER_INHERITANCE_CHANGED,
@ -76,19 +72,4 @@ public class GMUserEvent extends Event {
USER_ADDED, USER_ADDED,
USER_REMOVED, 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.");
}
}
} }

View File

@ -8,54 +8,43 @@ import org.bukkit.event.world.WorldInitEvent;
/** /**
* @author ElgarL * @author ElgarL
* *
* Handle new world creation from other plugins * Handle new world creation from other plugins
* *
*/ */
public class GMWorldListener implements Listener { public class GMWorldListener implements Listener {
private final GroupManager plugin; private final GroupManager plugin;
public GMWorldListener(GroupManager instance) { public GMWorldListener(final GroupManager instance) {
plugin = instance; plugin = instance;
registerEvents(); registerEvents();
} }
private void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(final WorldInitEvent event) {
final String worldName = event.getWorld().getName();
String worldName = event.getWorld().getName();
if (GroupManager.isLoaded() && !plugin.getWorldsHolder().isInList(worldName)) { if (GroupManager.isLoaded() && !plugin.getWorldsHolder().isInList(worldName)) {
GroupManager.logger.info("New world detected..."); GroupManager.logger.info("发现一个新的世界...");
GroupManager.logger.info("Creating data for: " + worldName); GroupManager.logger.info("创建新的数据: " + worldName);
if (plugin.getWorldsHolder().isWorldKnown("all_unnamed_worlds")) { if (plugin.getWorldsHolder().isWorldKnown("all_unnamed_worlds")) {
final String usersMirror = plugin.getWorldsHolder().getMirrorsUser().get("all_unnamed_worlds");
String usersMirror = plugin.getWorldsHolder().getMirrorsUser().get("all_unnamed_worlds"); final String groupsMirror = plugin.getWorldsHolder().getMirrorsGroup().get("all_unnamed_worlds");
String groupsMirror = plugin.getWorldsHolder().getMirrorsGroup().get("all_unnamed_worlds");
if (usersMirror != null) if (usersMirror != null)
plugin.getWorldsHolder().getMirrorsUser().put(worldName.toLowerCase(), usersMirror); plugin.getWorldsHolder().getMirrorsUser().put(worldName.toLowerCase(), usersMirror);
if (groupsMirror != null) if (groupsMirror != null)
plugin.getWorldsHolder().getMirrorsGroup().put(worldName.toLowerCase(), groupsMirror); plugin.getWorldsHolder().getMirrorsGroup().put(worldName.toLowerCase(), groupsMirror);
} }
plugin.getWorldsHolder().setupWorldFolder(worldName); plugin.getWorldsHolder().setupWorldFolder(worldName);
plugin.getWorldsHolder().loadWorld(worldName); plugin.getWorldsHolder().loadWorld(worldName);
if (plugin.getWorldsHolder().isInList(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 } else
GroupManager.logger.severe("Failed to configure this world."); GroupManager.logger.severe("自动配置失败 请联系开发者.");
} }
} }
private void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
} }

View File

@ -7,67 +7,46 @@ import org.bukkit.Server;
/** /**
* @author ElgarL * @author ElgarL
* *
* Handles all Event generation. * Handles all Event generation.
* *
*/ */
public class GroupManagerEventHandler { public class GroupManagerEventHandler {
private final Server server; private final Server server;
private final GroupManager plugin; private final GroupManager plugin;
public GroupManagerEventHandler(GroupManager plugin) { public GroupManagerEventHandler(final GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
this.server = plugin.getServer(); this.server = plugin.getServer();
} }
protected void callEvent(GMGroupEvent event) { public void callEvent(final GMSystemEvent.Action action) {
callEvent(new GMSystemEvent(action));
event.schedule(event);
} }
protected void callEvent(GMUserEvent event) { public void callEvent(final Group group, final GMGroupEvent.Action action) {
event.schedule(event);
}
protected void callEvent(GMSystemEvent event) {
event.schedule(event);
}
public void callEvent(Group group, GMGroupEvent.Action action) {
callEvent(new GMGroupEvent(group, 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)); callEvent(new GMGroupEvent(groupName, action));
} }
public void callEvent(User user, GMUserEvent.Action action) { public void callEvent(final String userName, final GMUserEvent.Action action) {
callEvent(new GMUserEvent(user, action));
}
public void callEvent(String userName, GMUserEvent.Action action) {
callEvent(new GMUserEvent(userName, action)); callEvent(new GMUserEvent(userName, action));
} }
public void callEvent(GMSystemEvent.Action action) { public void callEvent(final User user, final GMUserEvent.Action action) {
callEvent(new GMUserEvent(user, action));
callEvent(new GMSystemEvent(action));
} }
/** /**
* @return the plugin * @return the plugin
*/ */
public GroupManager getPlugin() { public GroupManager getPlugin() {
return plugin; return plugin;
} }
@ -75,8 +54,19 @@ public class GroupManagerEventHandler {
* @return the server * @return the server
*/ */
public Server getServer() { public Server getServer() {
return server; 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);
}
} }

View File

@ -31,7 +31,6 @@ import org.bukkit.entity.Player;
* @author gabrielcouto, ElgarL * @author gabrielcouto, ElgarL
*/ */
public class AnjoPermissionsHandler extends PermissionsReaderInterface { public class AnjoPermissionsHandler extends PermissionsReaderInterface {
WorldDataHolder ph = null; WorldDataHolder ph = null;
/** /**
@ -40,19 +39,16 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @param holder * @param holder
*/ */
public AnjoPermissionsHandler(final WorldDataHolder holder) { public AnjoPermissionsHandler(final WorldDataHolder holder) {
ph = holder; ph = holder;
} }
@Override @Override
public void addGroupInfo(final String name, final String path, final Object data) { public void addGroupInfo(final String name, final String path, final Object data) {
ph.getGroup(name).getVariables().addVar(path, data); ph.getGroup(name).getVariables().addVar(path, data);
} }
@Override @Override
public void addUserInfo(final String name, final String path, final Object data) { public void addUserInfo(final String name, final String path, final Object data) {
ph.getUser(name).getVariables().addVar(path, data); ph.getUser(name).getVariables().addVar(path, data);
} }
@ -65,7 +61,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean canGroupBuild(final String groupName) { public boolean canGroupBuild(final String groupName) {
final Group g = ph.getGroup(groupName); final Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return false; return false;
@ -81,9 +76,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return true if the user can build * @return true if the user can build
*/ */
public boolean canUserBuild(final String userName) { public boolean canUserBuild(final String userName) {
return getPermissionBoolean(userName, "build"); return getPermissionBoolean(userName, "build");
} }
/** /**
@ -99,7 +92,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkFullGMPermission(final User user, final String targetPermission, final Boolean checkBukkit) { public PermissionCheckResult checkFullGMPermission(final User user, final String targetPermission, final Boolean checkBukkit) {
/* /*
* Report no permissions under the following conditions. * Report no permissions under the following conditions.
* *
@ -108,14 +100,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
if (user == null || targetPermission == null || targetPermission.isEmpty() if (user == null || targetPermission == null || targetPermission.isEmpty()
|| (!Bukkit.getServer().getOnlineMode() && (checkPermission(user, "groupmanager.noofflineperms", false).resultType == PermissionCheckResult.Type.FOUND))) { || (!Bukkit.getServer().getOnlineMode() && (checkPermission(user, "groupmanager.noofflineperms", false).resultType == PermissionCheckResult.Type.FOUND))) {
final PermissionCheckResult result = new PermissionCheckResult(); final PermissionCheckResult result = new PermissionCheckResult();
result.accessLevel = targetPermission; result.accessLevel = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND; result.resultType = PermissionCheckResult.Type.NOTFOUND;
return result; return result;
} }
return checkPermission(user, targetPermission, checkBukkit); return checkPermission(user, targetPermission, checkBukkit);
} }
@ -128,7 +117,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkFullUserPermission(final User user, final String targetPermission) { public PermissionCheckResult checkFullUserPermission(final User user, final String targetPermission) {
return checkFullGMPermission(user, targetPermission, true); 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 * @return the node if permission is found. if not found, return null
*/ */
public PermissionCheckResult checkGroupOnlyPermission(final Group group, final String permission) { public PermissionCheckResult checkGroupOnlyPermission(final Group group, final String permission) {
group.sortPermissions(); group.sortPermissions();
final PermissionCheckResult result = new PermissionCheckResult(); final PermissionCheckResult result = new PermissionCheckResult();
result.owner = group; result.owner = group;
@ -172,38 +159,29 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkGroupPermissionWithInheritance(final Group start, final String targetPermission) { public PermissionCheckResult checkGroupPermissionWithInheritance(final Group start, final String targetPermission) {
if (start == null || targetPermission == null) { if (start == null || targetPermission == null) {
return null; return null;
} }
final LinkedList<Group> stack = new LinkedList<Group>(); final LinkedList<Group> stack = new LinkedList<Group>();
final List<Group> alreadyVisited = new ArrayList<Group>(); final List<Group> alreadyVisited = new ArrayList<Group>();
PermissionCheckResult result = new PermissionCheckResult(); PermissionCheckResult result = new PermissionCheckResult();
stack.push(start); stack.push(start);
alreadyVisited.add(start); alreadyVisited.add(start);
// Set defaults. // Set defaults.
result.askedPermission = targetPermission; result.askedPermission = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND; result.resultType = PermissionCheckResult.Type.NOTFOUND;
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
final Group now = stack.pop(); final Group now = stack.pop();
final PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission); final PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission);
if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) {
if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) {
resultNow.accessLevel = targetPermission; resultNow.accessLevel = targetPermission;
return resultNow; return resultNow;
} }
// Negation found so store for later // Negation found so store for later
// as we need to continue looking for an Exception. // as we need to continue looking for an Exception.
result = resultNow; result = resultNow;
} }
for (final String sonName : now.getInherits()) { for (final String sonName : now.getInherits()) {
final Group son = ph.getGroup(sonName); final Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son)) { if (son != null && !alreadyVisited.contains(son)) {
@ -213,7 +191,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
} }
} }
} }
return result; return result;
} }
@ -225,7 +202,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkUserOnlyPermission(final User user, final String permission) { public PermissionCheckResult checkUserOnlyPermission(final User user, final String permission) {
user.sortPermissions(); user.sortPermissions();
final PermissionCheckResult result = new PermissionCheckResult(); final PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = permission; result.askedPermission = permission;
@ -249,12 +225,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return true if permission was found. false if not, or was negated. * @return true if permission was found. false if not, or was negated.
*/ */
public boolean checkUserPermission(final User user, final String permission) { public boolean checkUserPermission(final User user, final String permission) {
final PermissionCheckResult result = checkFullGMPermission(user, permission, true); final PermissionCheckResult result = checkFullGMPermission(user, permission, true);
if (result.resultType == PermissionCheckResult.Type.EXCEPTION || result.resultType == PermissionCheckResult.Type.FOUND) { if (result.resultType == PermissionCheckResult.Type.EXCEPTION || result.resultType == PermissionCheckResult.Type.FOUND) {
return true; return true;
} }
return false; return false;
} }
@ -277,12 +251,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult.Type * @return PermissionCheckResult.Type
*/ */
public PermissionCheckResult.Type comparePermissionString(final String userAccessLevel, final String fullPermissionName) { public PermissionCheckResult.Type comparePermissionString(final String userAccessLevel, final String fullPermissionName) {
int userAccessLevelLength; int userAccessLevelLength;
if (userAccessLevel == null || fullPermissionName == null || fullPermissionName.length() == 0 || (userAccessLevelLength = userAccessLevel.length()) == 0) { if (userAccessLevel == null || fullPermissionName == null || fullPermissionName.length() == 0 || (userAccessLevelLength = userAccessLevel.length()) == 0) {
return PermissionCheckResult.Type.NOTFOUND; return PermissionCheckResult.Type.NOTFOUND;
} }
PermissionCheckResult.Type result = PermissionCheckResult.Type.FOUND; PermissionCheckResult.Type result = PermissionCheckResult.Type.FOUND;
int userAccessLevelOffset = 0; int userAccessLevelOffset = 0;
if (userAccessLevel.charAt(0) == '+') { if (userAccessLevel.charAt(0) == '+') {
@ -292,15 +264,12 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
userAccessLevelOffset = 1; userAccessLevelOffset = 1;
result = PermissionCheckResult.Type.NEGATION; result = PermissionCheckResult.Type.NEGATION;
} }
if (fullPermissionName.equals(userAccessLevel)) { if (fullPermissionName.equals(userAccessLevel)) {
return result; return result;
} }
if ("groupmanager.noofflineperms".equals(fullPermissionName)) { if ("groupmanager.noofflineperms".equals(fullPermissionName)) {
result = PermissionCheckResult.Type.NOTFOUND; result = PermissionCheckResult.Type.NOTFOUND;
} }
if ("*".regionMatches(0, userAccessLevel, userAccessLevelOffset, userAccessLevelLength - userAccessLevelOffset)) { if ("*".regionMatches(0, userAccessLevel, userAccessLevelOffset, userAccessLevelLength - userAccessLevelOffset)) {
return result; return result;
} }
@ -310,7 +279,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
} else { } else {
fullPermissionNameOffset = 0; fullPermissionNameOffset = 0;
} }
if (userAccessLevel.charAt(userAccessLevel.length() - 1) == '*') { if (userAccessLevel.charAt(userAccessLevel.length() - 1) == '*') {
return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, userAccessLevelLength - userAccessLevelOffset - 1) ? result : PermissionCheckResult.Type.NOTFOUND; return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, userAccessLevelLength - userAccessLevelOffset - 1) ? result : PermissionCheckResult.Type.NOTFOUND;
} }
@ -330,11 +298,8 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public List<String> getAllPlayersPermissions(final String userName) { public List<String> getAllPlayersPermissions(final String userName) {
final List<String> perms = new ArrayList<String>(); final List<String> perms = new ArrayList<String>();
perms.addAll(getAllPlayersPermissions(userName, true)); perms.addAll(getAllPlayersPermissions(userName, true));
return perms; return perms;
} }
@ -347,77 +312,55 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public Set<String> getAllPlayersPermissions(final String userName, final Boolean includeChildren) { public Set<String> getAllPlayersPermissions(final String userName, final Boolean includeChildren) {
final Set<String> playerPermArray = new LinkedHashSet<String>(); final Set<String> playerPermArray = new LinkedHashSet<String>();
final Set<String> overrides = new LinkedHashSet<String>(); final Set<String> overrides = new LinkedHashSet<String>();
// Add the players own permissions. // Add the players own permissions.
playerPermArray.addAll(populatePerms(ph.getUser(userName).getPermissionList(), includeChildren)); playerPermArray.addAll(populatePerms(ph.getUser(userName).getPermissionList(), includeChildren));
final ArrayList<String> alreadyProcessed = new ArrayList<String>(); final ArrayList<String> alreadyProcessed = new ArrayList<String>();
// fetch all group permissions // fetch all group permissions
for (final String group : getGroups(userName)) { for (final String group : getGroups(userName)) {
// Don't process a group more than once. // Don't process a group more than once.
if (!alreadyProcessed.contains(group)) { if (!alreadyProcessed.contains(group)) {
alreadyProcessed.add(group); alreadyProcessed.add(group);
Set<String> groupPermArray = new LinkedHashSet<String>(); Set<String> groupPermArray = new LinkedHashSet<String>();
if (group.startsWith("g:") && GroupManager.getGlobalGroups().hasGroup(group)) { if (group.startsWith("g:") && GroupManager.getGlobalGroups().hasGroup(group)) {
// GlobalGroups // GlobalGroups
groupPermArray = populatePerms(GroupManager.getGlobalGroups().getGroupsPermissions(group), includeChildren); groupPermArray = populatePerms(GroupManager.getGlobalGroups().getGroupsPermissions(group), includeChildren);
} else { } else {
// World Groups // World Groups
groupPermArray = populatePerms(ph.getGroup(group).getPermissionList(), includeChildren); groupPermArray = populatePerms(ph.getGroup(group).getPermissionList(), includeChildren);
} }
// Add all group permissions, unless negated by earlier permissions. // Add all group permissions, unless negated by earlier permissions.
for (final String perm : groupPermArray) { for (final String perm : groupPermArray) {
final boolean negated = (perm.startsWith("-")); final boolean negated = (perm.startsWith("-"));
// Overridden (Exception) permission defeats negation. // Overridden (Exception) permission defeats negation.
if (perm.startsWith("+")) { if (perm.startsWith("+")) {
overrides.add(perm.substring(1)); overrides.add(perm.substring(1));
continue; continue;
} }
// Perm doesn't already exists and there is no negation for it // 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) // 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)) if ((!negated && !playerPermArray.contains(perm) && !wildcardNegation(playerPermArray, perm))
|| (negated && !playerPermArray.contains(perm.substring(1)) && !wildcardNegation(playerPermArray, perm.substring(1)))) || (negated && !playerPermArray.contains(perm.substring(1)) && !wildcardNegation(playerPermArray, perm.substring(1))))
playerPermArray.add(perm); playerPermArray.add(perm);
} }
} }
} }
// Process overridden permissions // Process overridden permissions
final Iterator<String> itr = overrides.iterator(); final Iterator<String> itr = overrides.iterator();
while (itr.hasNext()) { while (itr.hasNext()) {
final String node = itr.next(); final String node = itr.next();
if (playerPermArray.contains("-" + node)) { if (playerPermArray.contains("-" + node)) {
playerPermArray.remove("-" + node); playerPermArray.remove("-" + node);
} }
playerPermArray.add(node); playerPermArray.add(node);
} }
// Collections.sort(playerPermArray, StringPermissionComparator.getInstance()); // Collections.sort(playerPermArray, StringPermissionComparator.getInstance());
return playerPermArray; return playerPermArray;
} }
@Override @Override
public Group getDefaultGroup() { public Group getDefaultGroup() {
return ph.getDefaultGroup(); return ph.getDefaultGroup();
} }
@ -429,7 +372,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroup(final String userName) { public String getGroup(final String userName) {
return ph.getUser(userName).getGroup().getName(); return ph.getUser(userName).getGroup().getName();
} }
@ -443,7 +385,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getGroupPermissionBoolean(final String group, final String variable) { public boolean getGroupPermissionBoolean(final String group, final String variable) {
final Group start = ph.getGroup(group); final Group start = ph.getGroup(group);
if (start == null) { if (start == null) {
return false; return false;
@ -465,7 +406,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getGroupPermissionDouble(final String group, final String variable) { public double getGroupPermissionDouble(final String group, final String variable) {
final Group start = ph.getGroup(group); final Group start = ph.getGroup(group);
if (start == null) { if (start == null) {
return -1; return -1;
@ -487,7 +427,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getGroupPermissionInteger(final String groupName, final String variable) { public int getGroupPermissionInteger(final String groupName, final String variable) {
final Group start = ph.getGroup(groupName); final Group start = ph.getGroup(groupName);
if (start == null) { if (start == null) {
return -1; return -1;
@ -509,7 +448,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupPermissionString(final String groupName, final String variable) { public String getGroupPermissionString(final String groupName, final String variable) {
final Group start = ph.getGroup(groupName); final Group start = ph.getGroup(groupName);
if (start == null) { if (start == null) {
return null; return null;
@ -529,7 +467,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupPrefix(final String groupName) { public String getGroupPrefix(final String groupName) {
final Group g = ph.getGroup(groupName); final Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return ""; return "";
@ -547,12 +484,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String[] getGroups(final String userName) { public String[] getGroups(final String userName) {
final ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup()); final ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup());
for (final Group subg : ph.getUser(userName).subGroupListCopy()) { for (final Group subg : ph.getUser(userName).subGroupListCopy()) {
allGroups.addAll(listAllGroupsInherited(subg)); allGroups.addAll(listAllGroupsInherited(subg));
} }
final String[] arr = new String[allGroups.size()]; final String[] arr = new String[allGroups.size()];
return allGroups.toArray(arr); return allGroups.toArray(arr);
} }
@ -565,7 +500,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupSuffix(final String groupName) { public String getGroupSuffix(final String groupName) {
final Group g = ph.getGroup(groupName); final Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return ""; return "";
@ -603,12 +537,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return -1; return -1;
} }
return data.getVariables().getVarDouble(path); return data.getVariables().getVarDouble(path);
} }
@Override @Override
public int getInfoInteger(final String entryName, final String path, final boolean isGroup) { public int getInfoInteger(final String entryName, final String path, final boolean isGroup) {
if (isGroup) { if (isGroup) {
final Group data = ph.getGroup(entryName); final Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -625,7 +557,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public String getInfoString(final String entryName, final String path, final boolean isGroup) { public String getInfoString(final String entryName, final String path, final boolean isGroup) {
if (isGroup) { if (isGroup) {
final Group data = ph.getGroup(entryName); final Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -651,7 +582,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getPermissionBoolean(final String user, final String variable) { public boolean getPermissionBoolean(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return false; return false;
@ -691,7 +621,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getPermissionDouble(final String user, final String variable) { public double getPermissionDouble(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1.0D; return -1.0D;
@ -731,7 +660,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getPermissionInteger(final String user, final String variable) { public int getPermissionInteger(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -771,7 +699,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getPermissionString(final String user, final String variable) { public String getPermissionString(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return ""; return "";
@ -810,9 +737,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return Name of player's primary group * @return Name of player's primary group
*/ */
public String getPrimaryGroup(final String user) { public String getPrimaryGroup(final String user) {
return getGroup(user); return getGroup(user);
} }
/** /**
@ -824,7 +749,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getUserPermissionBoolean(final String user, final String variable) { public boolean getUserPermissionBoolean(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return false; return false;
@ -841,7 +765,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getUserPermissionDouble(final String user, final String variable) { public double getUserPermissionDouble(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -858,7 +781,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getUserPermissionInteger(final String user, final String variable) { public int getUserPermissionInteger(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -875,7 +797,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getUserPermissionString(final String user, final String variable) { public String getUserPermissionString(final String user, final String variable) {
final User auser = ph.getUser(user); final User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return ""; return "";
@ -895,12 +816,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getUserPrefix(final String user) { public String getUserPrefix(final String user) {
final String prefix = ph.getUser(user).getVariables().getVarString("prefix"); final String prefix = ph.getUser(user).getVariables().getVarString("prefix");
if (prefix.length() != 0) { if (prefix.length() != 0) {
return prefix; return prefix;
} }
return getGroupPrefix(getGroup(user)); return getGroupPrefix(getGroup(user));
} }
@ -916,14 +835,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getUserSuffix(final String user) { public String getUserSuffix(final String user) {
final String suffix = ph.getUser(user).getVariables().getVarString("suffix"); final String suffix = ph.getUser(user).getVariables().getVarString("suffix");
if (suffix.length() != 0) { if (suffix.length() != 0) {
return suffix; return suffix;
} }
return getGroupSuffix(getGroup(user)); return getGroupSuffix(getGroup(user));
} }
/** /**
@ -935,7 +851,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean has(final Player player, final String permission) { public boolean has(final Player player, final String permission) {
return permission(player, permission); return permission(player, permission);
} }
@ -951,7 +866,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return true if it inherits the group. * @return true if it inherits the group.
*/ */
public boolean hasGroupInInheritance(final Group start, final String askedGroup) { public boolean hasGroupInInheritance(final Group start, final String askedGroup) {
if (start == null || askedGroup == null) { if (start == null || askedGroup == null) {
return false; return false;
} }
@ -992,7 +906,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean inGroup(final String name, final String group) { public boolean inGroup(final String name, final String group) {
if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) { if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) {
return true; return true;
} }
@ -1014,7 +927,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return the group that passed on test. null if no group passed. * @return the group that passed on test. null if no group passed.
*/ */
public ArrayList<String> listAllGroupsInherited(final Group start) { public ArrayList<String> listAllGroupsInherited(final Group start) {
if (start == null) { if (start == null) {
return null; return null;
} }
@ -1048,7 +960,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return The group if found. Null if not. * @return The group if found. Null if not.
*/ */
public Group nextGroupWithVariable(final Group start, final String targetVariable) { public Group nextGroupWithVariable(final Group start, final String targetVariable) {
if (start == null || targetVariable == null) { if (start == null || targetVariable == null) {
return null; return null;
} }
@ -1081,7 +992,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean permission(final Player player, final String permission) { public boolean permission(final Player player, final String permission) {
return checkUserPermission(ph.getUser(player.getName()).updatePlayer(player), 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 * @return true if the player has the permission
*/ */
public boolean permission(final String playerName, final String permission) { public boolean permission(final String playerName, final String permission) {
return checkUserPermission(ph.getUser(playerName), permission); return checkUserPermission(ph.getUser(playerName), permission);
} }
@Override @Override
public void removeGroupInfo(final String name, final String path) { public void removeGroupInfo(final String name, final String path) {
ph.getGroup(name).getVariables().removeVar(path); ph.getGroup(name).getVariables().removeVar(path);
} }
@Override @Override
public void removeUserInfo(final String name, final String path) { public void removeUserInfo(final String name, final String path) {
ph.getUser(name).getVariables().removeVar(path); ph.getUser(name).getVariables().removeVar(path);
} }
@ -1121,7 +1028,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
private Group breadthFirstSearch(final Group start, final String targerPermission) { private Group breadthFirstSearch(final Group start, final String targerPermission) {
if (start == null || targerPermission == null) { if (start == null || targerPermission == null) {
return null; return null;
} }
@ -1160,11 +1066,9 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
private PermissionCheckResult checkPermission(final User user, final String targetPermission, final Boolean checkBukkit) { private PermissionCheckResult checkPermission(final User user, final String targetPermission, final Boolean checkBukkit) {
PermissionCheckResult result = new PermissionCheckResult(); PermissionCheckResult result = new PermissionCheckResult();
result.accessLevel = targetPermission; result.accessLevel = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND; result.resultType = PermissionCheckResult.Type.NOTFOUND;
if (checkBukkit) { if (checkBukkit) {
// Check Bukkit perms to support plugins which add perms via code // Check Bukkit perms to support plugins which add perms via code
// (Heroes). // (Heroes).
@ -1176,78 +1080,54 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return result; return result;
} }
} }
final PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission); final PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission);
if (resultUser.resultType != PermissionCheckResult.Type.NOTFOUND) { if (resultUser.resultType != PermissionCheckResult.Type.NOTFOUND) {
resultUser.accessLevel = targetPermission; resultUser.accessLevel = targetPermission;
if (resultUser.resultType == PermissionCheckResult.Type.EXCEPTION) { if (resultUser.resultType == PermissionCheckResult.Type.EXCEPTION) {
return resultUser; return resultUser;
} }
result = resultUser; result = resultUser;
} }
// IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT AN EXCEPTION // IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT AN EXCEPTION
final PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission); final PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission);
if (resultGroup.resultType != PermissionCheckResult.Type.NOTFOUND) { if (resultGroup.resultType != PermissionCheckResult.Type.NOTFOUND) {
resultGroup.accessLevel = targetPermission; resultGroup.accessLevel = targetPermission;
if (resultGroup.resultType == PermissionCheckResult.Type.EXCEPTION) { if (resultGroup.resultType == PermissionCheckResult.Type.EXCEPTION) {
return resultGroup; return resultGroup;
} }
// Do not override higher level permissions with negations. // Do not override higher level permissions with negations.
if (result.resultType == PermissionCheckResult.Type.NOTFOUND) { if (result.resultType == PermissionCheckResult.Type.NOTFOUND) {
result = resultGroup; result = resultGroup;
} }
} }
// Do we have a high level negation? // Do we have a high level negation?
final boolean negated = (result.resultType == PermissionCheckResult.Type.NEGATION); final boolean negated = (result.resultType == PermissionCheckResult.Type.NEGATION);
// SUBGROUPS CHECK // SUBGROUPS CHECK
for (final Group subGroup : user.subGroupListCopy()) { for (final Group subGroup : user.subGroupListCopy()) {
final PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission); final PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission);
if (resultSubGroup.resultType != PermissionCheckResult.Type.NOTFOUND) { if (resultSubGroup.resultType != PermissionCheckResult.Type.NOTFOUND) {
resultSubGroup.accessLevel = targetPermission; resultSubGroup.accessLevel = targetPermission;
// Allow exceptions to override higher level negations // Allow exceptions to override higher level negations
// but low level negations can not remove higher level permissions. // but low level negations can not remove higher level permissions.
if (resultSubGroup.resultType == PermissionCheckResult.Type.EXCEPTION) { if (resultSubGroup.resultType == PermissionCheckResult.Type.EXCEPTION) {
return resultSubGroup; return resultSubGroup;
} else if ((resultSubGroup.resultType == PermissionCheckResult.Type.FOUND) && (result.resultType != PermissionCheckResult.Type.NEGATION) && !negated) { } else if ((resultSubGroup.resultType == PermissionCheckResult.Type.FOUND) && (result.resultType != PermissionCheckResult.Type.NEGATION) && !negated) {
result = resultSubGroup; result = resultSubGroup;
} else if ((resultSubGroup.resultType == PermissionCheckResult.Type.NEGATION) && !negated) { } else if ((resultSubGroup.resultType == PermissionCheckResult.Type.NEGATION) && !negated) {
result = resultSubGroup; result = resultSubGroup;
} }
} }
} }
// THEN IT RETURNS A NOT FOUND // THEN IT RETURNS A NOT FOUND
// OR THE RESULT OF THE SUBGROUP SEARCH. // OR THE RESULT OF THE SUBGROUP SEARCH.
return result; return result;
} }
private Set<String> populatePerms(final List<String> permsList, final boolean includeChildren) { private Set<String> populatePerms(final List<String> permsList, final boolean includeChildren) {
// Create a new array so it's modifiable. // Create a new array so it's modifiable.
final List<String> perms = new ArrayList<String>(permsList); final List<String> perms = new ArrayList<String>(permsList);
final Set<String> permArray = new LinkedHashSet<String>(); final Set<String> permArray = new LinkedHashSet<String>();
Boolean allPerms = false; Boolean allPerms = false;
// Allow * node to populate ALL permissions to Bukkit. // Allow * node to populate ALL permissions to Bukkit.
if (perms.contains("*")) { if (perms.contains("*")) {
permArray.addAll(GroupManager.BukkitPermissions.getAllRegisteredPermissions(includeChildren)); 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. // Remove the no offline perms node as this should not be given.
perms.remove("groupmanager.noofflineperms"); perms.remove("groupmanager.noofflineperms");
} }
for (final String perm : perms) { for (final String perm : perms) {
/** /**
* all permission sets are passed here pre-sorted, alphabetically. * all permission sets are passed here pre-sorted, alphabetically.
@ -1264,13 +1143,10 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* other than *. * other than *.
*/ */
final boolean negated = perm.startsWith("-"); final boolean negated = perm.startsWith("-");
if (!permArray.contains(perm)) { if (!permArray.contains(perm)) {
permArray.add(perm); permArray.add(perm);
if ((negated) && (permArray.contains(perm.substring(1)))) if ((negated) && (permArray.contains(perm.substring(1))))
permArray.remove(perm.substring(1)); permArray.remove(perm.substring(1));
/** /**
* Process child nodes if required, * Process child nodes if required,
* or this is a negated node AND we used * to include all * 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. * in which case we need to remove all children of that node.
*/ */
if ((includeChildren) || (negated && allPerms)) { if ((includeChildren) || (negated && allPerms)) {
final Map<String, Boolean> children = GroupManager.BukkitPermissions.getAllChildren((negated ? perm.substring(1) : perm), new LinkedHashSet<String>()); final Map<String, Boolean> children = GroupManager.BukkitPermissions.getAllChildren((negated ? perm.substring(1) : perm), new LinkedHashSet<String>());
if (children != null) { if (children != null) {
if (negated) if (negated)
if (allPerms) { if (allPerms) {
// Remove children of negated nodes // Remove children of negated nodes
for (final String child : children.keySet()) for (final String child : children.keySet())
if (children.get(child)) if (children.get(child))
if (permArray.contains(child)) if (permArray.contains(child))
permArray.remove(child); permArray.remove(child);
} else { } else {
// Add child nodes // Add child nodes
for (final String child : children.keySet()) for (final String child : children.keySet())
if (children.get(child)) if (children.get(child))
@ -1303,7 +1174,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
} }
} }
} }
return permArray; return permArray;
} }
@ -1315,14 +1185,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return * @return
*/ */
private boolean wildcardNegation(final Set<String> playerPermArray, final String node) { private boolean wildcardNegation(final Set<String> playerPermArray, final String node) {
/* /*
* Check for a negated parent with a wildcard or negated permission * Check for a negated parent with a wildcard or negated permission
*/ */
if (playerPermArray.contains("-" + node)) if (playerPermArray.contains("-" + node))
return true; return true;
final String[] parts = node.split("\\."); final String[] parts = node.split("\\.");
final StringBuilder builder = new StringBuilder(node.length()); final StringBuilder builder = new StringBuilder(node.length());
for (final String part : parts) { for (final String part : parts) {
@ -1331,16 +1198,13 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
GroupManager.logger.fine("Wildcard Negation found for " + node); GroupManager.logger.fine("Wildcard Negation found for " + node);
return true; return true;
} }
builder.deleteCharAt(builder.length() - 1); builder.deleteCharAt(builder.length() - 1);
builder.append(part).append('.'); builder.append(part).append('.');
} }
/* /*
* No negated parent found so return false. * No negated parent found so return false.
*/ */
GroupManager.logger.fine("No Negation found for " + node); GroupManager.logger.fine("No Negation found for " + node);
return false; return false;
} }
} }

View File

@ -14,7 +14,6 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA. * USA.
*/ */
package org.anjocaido.groupmanager.permissions; package org.anjocaido.groupmanager.permissions;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -71,28 +70,21 @@ public class BukkitPermissions {
protected LinkedHashMap<String, Permission> registeredPermissions = new LinkedHashMap<String, Permission>(); protected LinkedHashMap<String, Permission> registeredPermissions = new LinkedHashMap<String, Permission>();
protected GroupManager plugin; protected GroupManager plugin;
protected boolean dumpAllPermissions = true; protected boolean dumpAllPermissions = true;
protected boolean dumpMatchedPermissions = true; protected boolean dumpMatchedPermissions = true;
private boolean player_join = false; private boolean player_join = false;
public BukkitPermissions(final GroupManager plugin) { public BukkitPermissions(final GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
this.reset(); this.reset();
this.registerEvents(); this.registerEvents();
GroupManager.logger.info("启用 Bukkit Permissions 支持.");
GroupManager.logger.info("Superperms support enabled.");
} }
public void collectPermissions() { public void collectPermissions() {
registeredPermissions.clear(); registeredPermissions.clear();
for (final Permission perm : Bukkit.getPluginManager().getPermissions()) { for (final Permission perm : Bukkit.getPluginManager().getPermissions()) {
registeredPermissions.put(perm.getName().toLowerCase(), perm); registeredPermissions.put(perm.getName().toLowerCase(), perm);
} }
} }
/** /**
@ -106,17 +98,13 @@ public class BukkitPermissions {
* @return Map of child permissions * @return Map of child permissions
*/ */
public Map<String, Boolean> getAllChildren(final String node, final Set<String> playerPermArray) { public Map<String, Boolean> getAllChildren(final String node, final Set<String> playerPermArray) {
final LinkedList<String> stack = new LinkedList<String>(); final LinkedList<String> stack = new LinkedList<String>();
final Map<String, Boolean> alreadyVisited = new HashMap<String, Boolean>(); final Map<String, Boolean> alreadyVisited = new HashMap<String, Boolean>();
stack.push(node); stack.push(node);
alreadyVisited.put(node, true); alreadyVisited.put(node, true);
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
final String now = stack.pop(); final String now = stack.pop();
final Map<String, Boolean> children = getChildren(now); final Map<String, Boolean> children = getChildren(now);
if ((children != null) && (!playerPermArray.contains("-" + now))) { if ((children != null) && (!playerPermArray.contains("-" + now))) {
for (final String childName : children.keySet()) { for (final String childName : children.keySet()) {
if (!alreadyVisited.containsKey(childName)) { if (!alreadyVisited.containsKey(childName)) {
@ -129,7 +117,6 @@ public class BukkitPermissions {
alreadyVisited.remove(node); alreadyVisited.remove(node);
if (!alreadyVisited.isEmpty()) if (!alreadyVisited.isEmpty())
return alreadyVisited; return alreadyVisited;
return null; return null;
} }
@ -141,13 +128,10 @@ public class BukkitPermissions {
* @return List of all permission nodes * @return List of all permission nodes
*/ */
public List<String> getAllRegisteredPermissions(final boolean includeChildren) { public List<String> getAllRegisteredPermissions(final boolean includeChildren) {
final List<String> perms = new ArrayList<String>(); final List<String> perms = new ArrayList<String>();
for (final String key : registeredPermissions.keySet()) { for (final String key : registeredPermissions.keySet()) {
if (!perms.contains(key)) { if (!perms.contains(key)) {
perms.add(key); perms.add(key);
if (includeChildren) { if (includeChildren) {
final Map<String, Boolean> children = getAllChildren(key, new HashSet<String>()); final Map<String, Boolean> children = getAllChildren(key, new HashSet<String>());
if (children != null) { if (children != null) {
@ -157,7 +141,6 @@ public class BukkitPermissions {
} }
} }
} }
} }
return perms; return perms;
} }
@ -171,20 +154,16 @@ public class BukkitPermissions {
* @return Map of child permissions * @return Map of child permissions
*/ */
public Map<String, Boolean> getChildren(final String node) { public Map<String, Boolean> getChildren(final String node) {
final Permission perm = registeredPermissions.get(node.toLowerCase()); final Permission perm = registeredPermissions.get(node.toLowerCase());
if (perm == null) if (perm == null)
return null; return null;
return perm.getChildren(); return perm.getChildren();
} }
/** /**
* @return the player_join * @return the player_join
*/ */
public boolean isPlayer_join() { public boolean isPlayer_join() {
return player_join; return player_join;
} }
@ -195,9 +174,7 @@ public class BukkitPermissions {
* @return List<String> of permissions * @return List<String> of permissions
*/ */
public List<String> listPerms(final Player player) { public List<String> listPerms(final Player player) {
final List<String> perms = new ArrayList<String>(); final List<String> perms = new ArrayList<String>();
/* /*
* // All permissions registered with Bukkit for this player * // All permissions registered with Bukkit for this player
* PermissionAttachment attachment = this.attachments.get(player); * PermissionAttachment attachment = this.attachments.get(player);
@ -207,7 +184,6 @@ public class BukkitPermissions {
* attachment.getPermissions().entrySet()){ perms.add(" " + * attachment.getPermissions().entrySet()){ perms.add(" " +
* entry.getKey() + " = " + entry.getValue()); } * entry.getKey() + " = " + entry.getValue()); }
*/ */
perms.add("Effective Permissions:"); perms.add("Effective Permissions:");
for (final PermissionAttachmentInfo info : player.getEffectivePermissions()) { for (final PermissionAttachmentInfo info : player.getEffectivePermissions()) {
if (info.getValue() == true) if (info.getValue() == true)
@ -220,7 +196,6 @@ public class BukkitPermissions {
* Remove all attachments in case of a restart or reload. * Remove all attachments in case of a restart or reload.
*/ */
public void removeAllAttachments() { public void removeAllAttachments() {
/* /*
* Remove all attachments. * Remove all attachments.
*/ */
@ -231,7 +206,6 @@ public class BukkitPermissions {
} }
public void reset() { public void reset() {
/* /*
* collect new permissions * collect new permissions
* and register all attachments. * and register all attachments.
@ -245,7 +219,6 @@ public class BukkitPermissions {
* the player_join to set * the player_join to set
*/ */
public void setPlayer_join(final boolean player_join) { public void setPlayer_join(final boolean player_join) {
this.player_join = player_join; this.player_join = player_join;
} }
@ -253,14 +226,12 @@ public class BukkitPermissions {
* force Bukkit to update every OnlinePlayers permissions. * force Bukkit to update every OnlinePlayers permissions.
*/ */
public void updateAllPlayers() { public void updateAllPlayers() {
for (final Player player : Bukkit.getServer().getOnlinePlayers()) { for (final Player player : Bukkit.getServer().getOnlinePlayers()) {
updatePermissions(player); updatePermissions(player);
} }
} }
public void updatePermissions(final Player player) { public void updatePermissions(final Player player) {
this.updatePermissions(player, null); this.updatePermissions(player, null);
} }
@ -272,20 +243,15 @@ public class BukkitPermissions {
* @param world * @param world
*/ */
public void updatePermissions(final Player player, String world) { public void updatePermissions(final Player player, String world) {
if (player == null || !GroupManager.isLoaded()) { if (player == null || !GroupManager.isLoaded()) {
return; return;
} }
final String name = player.getName(); final String name = player.getName();
// Reset the User objects player reference. // Reset the User objects player reference.
final User user = plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(name); final User user = plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(name);
if (user != null) if (user != null)
user.updatePlayer(player); user.updatePlayer(player);
PermissionAttachment attachment; PermissionAttachment attachment;
// Find the players current attachment, or add a new one. // Find the players current attachment, or add a new one.
if (this.attachments.containsKey(name)) { if (this.attachments.containsKey(name)) {
attachment = this.attachments.get(name); attachment = this.attachments.get(name);
@ -293,26 +259,21 @@ public class BukkitPermissions {
attachment = player.addAttachment(plugin); attachment = player.addAttachment(plugin);
this.attachments.put(name, attachment); this.attachments.put(name, attachment);
} }
if (world == null) { if (world == null) {
world = player.getWorld().getName(); world = player.getWorld().getName();
} }
// Add all permissions for this player (GM only) // Add all permissions for this player (GM only)
// child nodes will be calculated by Bukkit. // child nodes will be calculated by Bukkit.
List<String> playerPermArray = new ArrayList<String>(plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getAllPlayersPermissions(name, false)); List<String> playerPermArray = new ArrayList<String>(plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getAllPlayersPermissions(name, false));
final LinkedHashMap<String, Boolean> newPerms = new LinkedHashMap<String, Boolean>(); final LinkedHashMap<String, Boolean> newPerms = new LinkedHashMap<String, Boolean>();
// Sort the perm list by parent/child, so it will push to superperms // Sort the perm list by parent/child, so it will push to superperms
// correctly. // correctly.
playerPermArray = sort(playerPermArray); playerPermArray = sort(playerPermArray);
Boolean value = false; Boolean value = false;
for (final String permission : playerPermArray) { for (final String permission : playerPermArray) {
value = (!permission.startsWith("-")); value = (!permission.startsWith("-"));
newPerms.put((value ? permission : permission.substring(1)), value); newPerms.put((value ? permission : permission.substring(1)), value);
} }
/* /*
* Do not push any perms to bukkit if... * Do not push any perms to bukkit if...
* We are in offline mode * We are in offline mode
@ -322,14 +283,12 @@ public class BukkitPermissions {
removeAttachment(name); removeAttachment(name);
return; return;
} }
/** /**
* This is put in place until such a time as Bukkit pull 466 is * This is put in place until such a time as Bukkit pull 466 is
* implemented https://github.com/Bukkit/Bukkit/pull/466 * implemented https://github.com/Bukkit/Bukkit/pull/466
*/ */
try { // Codename_B source try { // Codename_B source
synchronized (attachment.getPermissible()) { synchronized (attachment.getPermissible()) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Map<String, Boolean> orig = (Map<String, Boolean>) permissions.get(attachment); final Map<String, Boolean> orig = (Map<String, Boolean>) permissions.get(attachment);
// Clear the map (faster than removing the attachment and // Clear the map (faster than removing the attachment and
@ -339,14 +298,12 @@ public class BukkitPermissions {
orig.putAll(newPerms); orig.putAll(newPerms);
// That's all folks! // That's all folks!
attachment.getPermissible().recalculatePermissions(); attachment.getPermissible().recalculatePermissions();
} }
} catch (final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
} catch (final IllegalAccessException e) { } catch (final IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
GroupManager.logger.finest("Attachment updated for: " + name); GroupManager.logger.finest("Attachment updated for: " + name);
} }
@ -354,15 +311,12 @@ public class BukkitPermissions {
* force Bukkit to update this Players permissions. * force Bukkit to update this Players permissions.
*/ */
public void updatePlayer(final Player player) { public void updatePlayer(final Player player) {
if (player != null) if (player != null)
this.updatePermissions(player, null); this.updatePermissions(player, null);
} }
private void registerEvents() { private void registerEvents() {
final PluginManager manager = plugin.getServer().getPluginManager(); final PluginManager manager = plugin.getServer().getPluginManager();
manager.registerEvents(new PlayerEvents(), plugin); manager.registerEvents(new PlayerEvents(), plugin);
manager.registerEvents(new BukkitEvents(), plugin); manager.registerEvents(new BukkitEvents(), plugin);
} }
@ -373,7 +327,6 @@ public class BukkitPermissions {
* @param player * @param player
*/ */
private void removeAttachment(final String playerName) { private void removeAttachment(final String playerName) {
if (attachments.containsKey(playerName)) { if (attachments.containsKey(playerName)) {
attachments.get(playerName).remove(); attachments.get(playerName).remove();
attachments.remove(playerName); attachments.remove(playerName);
@ -387,9 +340,7 @@ public class BukkitPermissions {
* @return List sorted for priority * @return List sorted for priority
*/ */
private List<String> sort(final List<String> permList) { private List<String> sort(final List<String> permList) {
final List<String> result = new ArrayList<String>(); final List<String> result = new ArrayList<String>();
for (final String key : permList) { for (final String key : permList) {
/* /*
* Ignore stupid plugins which add empty permission nodes. * 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 String a = key.charAt(0) == '-' ? key.substring(1) : key;
final Map<String, Boolean> allchildren = GroupManager.BukkitPermissions.getAllChildren(a, new HashSet<String>()); final Map<String, Boolean> allchildren = GroupManager.BukkitPermissions.getAllChildren(a, new HashSet<String>());
if (allchildren != null) { if (allchildren != null) {
final ListIterator<String> itr = result.listIterator(); final ListIterator<String> itr = result.listIterator();
while (itr.hasNext()) { while (itr.hasNext()) {
final String node = itr.next(); final String node = itr.next();
final String b = node.charAt(0) == '-' ? node.substring(1) : node; final String b = node.charAt(0) == '-' ? node.substring(1) : node;
// Insert the parent node before the child // Insert the parent node before the child
if (allchildren.containsKey(b)) { if (allchildren.containsKey(b)) {
itr.set(key); itr.set(key);
@ -417,25 +365,20 @@ public class BukkitPermissions {
result.add(key); result.add(key);
} }
} }
return result; return result;
} }
protected class BukkitEvents implements Listener { protected class BukkitEvents implements Listener {
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPluginDisable(final PluginDisableEvent event) { public void onPluginDisable(final PluginDisableEvent event) {
collectPermissions(); collectPermissions();
// updateAllPlayers(); // updateAllPlayers();
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPluginEnable(final PluginEnableEvent event) { public void onPluginEnable(final PluginEnableEvent event) {
if (!GroupManager.isLoaded()) if (!GroupManager.isLoaded())
return; return;
collectPermissions(); collectPermissions();
updateAllPlayers(); updateAllPlayers();
} }
@ -448,32 +391,24 @@ public class BukkitPermissions {
* *
*/ */
protected class PlayerEvents implements Listener { protected class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChangeWorld(final PlayerChangedWorldEvent event) { // has changed worlds public void onPlayerChangeWorld(final PlayerChangedWorldEvent event) { // has changed worlds
updatePermissions(event.getPlayer(), event.getPlayer().getWorld().getName()); updatePermissions(event.getPlayer(), event.getPlayer().getWorld().getName());
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(final PlayerJoinEvent event) { public void onPlayerJoin(final PlayerJoinEvent event) {
setPlayer_join(true); setPlayer_join(true);
final Player player = event.getPlayer(); final Player player = event.getPlayer();
GroupManager.logger.finest("玩家进入游戏: " + player.getName());
GroupManager.logger.finest("Player Join event: " + player.getName());
/* /*
* Tidy up any lose ends * Tidy up any lose ends
*/ */
removeAttachment(player.getName()); removeAttachment(player.getName());
// force GM to create the player if they are not already listed. // force GM to create the player if they are not already listed.
plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(player.getUniqueId().toString(), player.getName()); plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(player.getUniqueId().toString(), player.getName());
setPlayer_join(false); setPlayer_join(false);
updatePermissions(event.getPlayer()); updatePermissions(event.getPlayer());
setPlayer_join(false); setPlayer_join(false);
} }
@ -482,17 +417,13 @@ public class BukkitPermissions {
*/ */
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerQuit(final PlayerQuitEvent event) { public void onPlayerQuit(final PlayerQuitEvent event) {
if (!GroupManager.isLoaded()) if (!GroupManager.isLoaded())
return; return;
final Player player = event.getPlayer(); final Player player = event.getPlayer();
/* /*
* force remove any attachments as bukkit may not * force remove any attachments as bukkit may not
*/ */
removeAttachment(player.getName()); removeAttachment(player.getName());
} }
} }
} }

View File

@ -9,15 +9,14 @@ import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class GMLoggerHandler extends ConsoleHandler { public class GMLoggerHandler extends ConsoleHandler {
@Override @Override
public void publish(LogRecord record) { public void publish(final LogRecord record) {
final String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage();
String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage();
if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) { if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) {
System.err.println(message); System.err.println(message);
} else { } else {

View File

@ -6,11 +6,10 @@ package org.anjocaido.groupmanager.utils;
/** /**
* Just a list of commands for this plugin * Just a list of commands for this plugin
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public enum GroupManagerPermissions { public enum GroupManagerPermissions {
manuadd, manuadd,
manudel, manudel,
manuaddsub, manuaddsub,

View File

@ -7,18 +7,27 @@ package org.anjocaido.groupmanager.utils;
import java.util.Comparator; import java.util.Comparator;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class StringPermissionComparator implements Comparator<String> { public class StringPermissionComparator implements Comparator<String> {
@Override private static StringPermissionComparator instance;
public int compare(String permA, String permB) {
boolean ap = permA.startsWith("+"); public static StringPermissionComparator getInstance() {
boolean bp = permB.startsWith("+");
boolean am = permA.startsWith("-"); if (instance == null) {
boolean bm = permB.startsWith("-"); 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) { if (ap && bp) {
return 0; return 0;
} }
@ -39,14 +48,4 @@ public class StringPermissionComparator implements Comparator<String> {
} }
return permA.compareToIgnoreCase(permB); return permA.compareToIgnoreCase(permB);
} }
private static StringPermissionComparator instance;
public static StringPermissionComparator getInstance() {
if (instance == null) {
instance = new StringPermissionComparator();
}
return instance;
}
} }

View File

@ -23,32 +23,38 @@ import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.data.Group; import org.anjocaido.groupmanager.data.Group;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class Tasks { public abstract class Tasks {
/** /**
* Gets the exception stack trace as a string. * Appends a string to a file
* *
* @param exception * @param data
* @return stack trace as a string * @param file
*/ */
public static String getStackTraceAsString(Exception exception) { public static void appendStringToFile(final String data, final String file) throws IOException {
final FileWriter outStream = new FileWriter("." + System.getProperty("file.separator") + file, true);
StringWriter sw = new StringWriter(); final BufferedWriter out = new BufferedWriter(outStream);
PrintWriter pw = new PrintWriter(sw); data.replaceAll("\n", System.getProperty("line.separator"));
exception.printStackTrace(pw); out.append(new SimpleDateFormat("yyyy-MM-dd HH-mm").format(System.currentTimeMillis()));
return sw.toString(); 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 { public static void copy(final File src, final File dst) throws IOException {
final InputStream in = new FileInputStream(src);
InputStream in = src; copy(in, dst);
OutputStream out = new FileOutputStream(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 // Transfer bytes from in to out
byte[] buf = new byte[1024]; final byte[] buf = new byte[1024];
int len; int len;
while ((len = in.read(buf)) > 0) { while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len); out.write(buf, 0, len);
@ -56,58 +62,12 @@ public abstract class Tasks {
out.close(); out.close();
try { try {
in.close(); in.close();
} catch (Exception e) { } catch (final 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) {
}
}
}
}
} }
} }
public static String getDateString() { public static String getDateString() {
final GregorianCalendar now = new GregorianCalendar();
GregorianCalendar now = new GregorianCalendar();
String date = ""; String date = "";
date += now.get(Calendar.DAY_OF_MONTH); date += now.get(Calendar.DAY_OF_MONTH);
date += "-"; date += "-";
@ -117,38 +77,7 @@ public abstract class Tasks {
return date; return date;
} }
public static String getStringListInString(List<String> list) { public static String getGroupListInString(final List<Group> 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<Group> list) {
if (list == null) { if (list == null) {
return ""; return "";
} }
@ -162,8 +91,48 @@ public abstract class Tasks {
return result; 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<String> 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) if (arr.length == 0)
return ""; return "";
String out = arr[0].toString(); String out = arr[0].toString();
@ -172,4 +141,20 @@ public abstract class Tasks {
return out; 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) {
}
}
}
}
}
}
} }

View File

@ -1,5 +1,5 @@
name: GroupManager name: GroupManager
version: ${project.version}(YUMC) version: ${project.version}-(YUMC)
main: org.anjocaido.groupmanager.GroupManager main: org.anjocaido.groupmanager.GroupManager
website: http://ess.khhq.net/wiki/Group_Manager 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. description: Provides on-the-fly system for permissions system created by Nijikokun. But all in memory, and with flat-file saving schedule.