1
0
mirror of https://e.coding.net/circlecloud/GroupManager.git synced 2024-11-21 01:39:09 +00:00

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

Signed-off-by: 502647092 <jtb1@163.com>
This commit is contained in:
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;
/**
*
*
* @author gabrielcouto
*/
public class GMConfiguration {
private boolean allowCommandBlocks = false;
private boolean opOverride = true;
private boolean toggleValidate = true;
@ -29,14 +28,11 @@ public class GMConfiguration {
private Integer backupDuration = 24;
private String loggerLevel = "OFF";
private Map<String, Object> mirrorsMap;
private GroupManager plugin;
private final GroupManager plugin;
private Map<String, Object> GMconfig;
public GMConfiguration(GroupManager plugin) {
public GMConfiguration(final GroupManager plugin) {
this.plugin = plugin;
/*
* Set defaults
*/
@ -46,102 +42,118 @@ public class GMConfiguration {
saveInterval = 10;
backupDuration = 24;
loggerLevel = "OFF";
load();
}
public void adjustLoggerLevel() {
try {
GroupManager.logger.setLevel(Level.parse(loggerLevel));
return;
} catch (final Exception e) {
}
GroupManager.logger.setLevel(Level.INFO);
}
public Integer getBackupDuration() {
return backupDuration;
}
public Map<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")
public void load() {
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs();
}
File configFile = new File(plugin.getDataFolder(), "config.yml");
final File configFile = new File(plugin.getDataFolder(), "config.yml");
if (!configFile.exists()) {
try {
Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile);
} catch (IOException ex) {
} catch (final IOException ex) {
GroupManager.logger.log(Level.SEVERE, "Error creating a new config.yml", ex);
}
}
Yaml configYAML = new Yaml(new SafeConstructor());
final Yaml configYAML = new Yaml(new SafeConstructor());
try {
FileInputStream configInputStream = new FileInputStream(configFile);
final FileInputStream configInputStream = new FileInputStream(configFile);
GMconfig = (Map<String, Object>) configYAML.load(new UnicodeReader(configInputStream));
configInputStream.close();
} catch (Exception ex) {
} catch (final Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex);
}
/*
* Read our config settings and store them for reading later.
*/
try {
Map<String, Object> config = getElement("config", getElement("settings", GMconfig));
final Map<String, Object> config = getElement("config", getElement("settings", GMconfig));
try {
allowCommandBlocks = (Boolean) config.get("allow_commandblocks");
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'allow_commandblocks' node. Using default settings", ex);
}
try {
opOverride = (Boolean) config.get("opOverrides");
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'opOverrides' node. Using default settings", ex);
}
try {
toggleValidate = (Boolean) config.get("validate_toggle");
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'validate_toggle' node. Using default settings", ex);
}
/*
* data node for save/backup timers.
*/
try {
Map<String, Object> save = getElement("save", getElement("data", getElement("settings", GMconfig)));
final Map<String, Object> save = getElement("save", getElement("data", getElement("settings", GMconfig)));
try {
saveInterval = (Integer) save.get("minutes");
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'minutes' node. Using default setting", ex);
}
try {
backupDuration = (Integer) save.get("hours");
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'hours' node. Using default setting", ex);
}
} catch (Exception ex) {
} catch (final Exception ex) {
GroupManager.logger.log(Level.SEVERE, "Missing or corrupt 'data' node. Using default settings", ex);
}
Object level = ((Map<String, String>) getElement("settings", GMconfig).get("logging")).get("level");
final Object level = ((Map<String, String>) getElement("settings", GMconfig).get("logging")).get("level");
if (level instanceof String)
loggerLevel = (String) level;
/*
* Store our mirrors map for parsing later.
*/
mirrorsMap = (Map<String, Object>) ((Map<String, Object>) GMconfig.get("settings")).get("mirrors");
if (mirrorsMap == null)
throw new Exception();
} catch (Exception ex) {
} catch (final Exception ex) {
/*
* Flag the error and use defaults
*/
GroupManager.logger.log(Level.SEVERE, "There are errors in your config.yml. Using default settings", ex);
mirrorsMap = new HashMap<String, Object>();
}
// Setup defaults
@ -150,59 +162,10 @@ public class GMConfiguration {
}
@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)) {
throw new IllegalArgumentException("The config.yml has no '" + element + ".\n");
}
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
*
*
*/
public class GlobalGroups {
private GroupManager plugin;
private final GroupManager plugin;
// private Yaml GGroups;
private final Map<String, Group> groups = Collections.synchronizedMap(new HashMap<String, Group>());
protected long timeStampGroups = 0;
protected boolean haveGroupsChanged = false;
protected File GlobalGroupsFile = null;
public GlobalGroups(GroupManager plugin) {
public GlobalGroups(final GroupManager plugin) {
this.plugin = plugin;
load();
}
/**
* Adds a group, or replaces an existing one.
*
* @param groupToAdd
*/
public void addGroup(Group groupToAdd) {
// Create a new group if it already exists
if (hasGroup(groupToAdd.getName())) {
groupToAdd = groupToAdd.clone();
removeGroup(groupToAdd.getName());
}
newGroup(groupToAdd);
haveGroupsChanged = true;
if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
}
/**
* Returns a PermissionCheckResult of the permission node for the group to
* be tested against.
*
* @param groupName
* @param permissionNode
* @return PermissionCheckResult object
*/
public PermissionCheckResult checkPermission(final String groupName, final String permissionNode) {
final PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = permissionNode;
result.resultType = PermissionCheckResult.Type.NOTFOUND;
if (!hasGroup(groupName))
return result;
final Group tempGroup = groups.get(groupName.toLowerCase());
if (tempGroup.hasSamePermissionNode(permissionNode))
result.resultType = PermissionCheckResult.Type.FOUND;
if (tempGroup.hasSamePermissionNode("-" + permissionNode))
result.resultType = PermissionCheckResult.Type.NEGATION;
if (tempGroup.hasSamePermissionNode("+" + permissionNode))
result.resultType = PermissionCheckResult.Type.EXCEPTION;
return result;
}
/**
* @return the globalGroupsFile
*/
public File getGlobalGroupsFile() {
return GlobalGroupsFile;
}
/**
* Returns the Global Group or null if it doesn't exist.
*
* @param groupName
* @return Group object
*/
public Group getGroup(final String groupName) {
if (!hasGroup(groupName))
return null;
return groups.get(groupName.toLowerCase());
}
/**
*
* @return a collection of the groups
*/
public Group[] getGroupList() {
synchronized (groups) {
return groups.values().toArray(new Group[0]);
}
}
/**
* Returns a List of all permission nodes for this group null if none
*
* @param groupName
* @return List of all group names
*/
public List<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
*/
public boolean haveGroupsChanged() {
if (this.haveGroupsChanged) {
return true;
}
synchronized (groups) {
for (Group g : groups.values()) {
for (final Group g : groups.values()) {
if (g.isChanged()) {
return true;
}
@ -62,85 +169,48 @@ public class GlobalGroups {
return false;
}
/**
* @return the timeStampGroups
*/
public long getTimeStampGroups() {
return timeStampGroups;
}
/**
* @param timeStampGroups
* the timeStampGroups to set
*/
protected void setTimeStampGroups(long timeStampGroups) {
this.timeStampGroups = timeStampGroups;
}
/**
* @param haveGroupsChanged
* the haveGroupsChanged to set
*/
public void setGroupsChanged(boolean haveGroupsChanged) {
this.haveGroupsChanged = haveGroupsChanged;
}
@SuppressWarnings("unchecked")
public void load() {
Yaml GGroupYAML = new Yaml(new SafeConstructor());
final Yaml GGroupYAML = new Yaml(new SafeConstructor());
Map<String, Object> GGroups;
GroupManager.setLoaded(false);
// READ globalGroups FILE
if (GlobalGroupsFile == null)
GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml");
if (!GlobalGroupsFile.exists()) {
try {
// Create a new file if it doesn't exist.
Tasks.copy(plugin.getResourceAsStream("globalgroups.yml"), GlobalGroupsFile);
} catch (IOException ex) {
} catch (final IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
/*
* Load the YAML file.
*/
try {
FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile);
final FileInputStream groupsInputStream = new FileInputStream(GlobalGroupsFile);
GGroups = (Map<String, Object>) GGroupYAML.load(new UnicodeReader(groupsInputStream));
groupsInputStream.close();
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + GlobalGroupsFile.getPath(), ex);
} catch (final Exception ex) {
throw new IllegalArgumentException("下列文件无法被解析.\n" + GlobalGroupsFile.getPath(), ex);
}
// Clear out old groups
resetGlobalGroups();
if (!GGroups.keySet().isEmpty()) {
// Read all global groups
Map<String, Object> allGroups = new HashMap<String, Object>();
try {
allGroups = (Map<String, Object>) GGroups.get("groups");
} catch (Exception ex) {
} catch (final Exception ex) {
// ex.printStackTrace();
throw new IllegalArgumentException("Your " + GlobalGroupsFile.getPath() + " file is invalid. See console for details.", ex);
throw new IllegalArgumentException("你的 " + GlobalGroupsFile.getPath() + " 文件不正确. 请查看控制台错误.", ex);
}
// Load each groups permissions list.
if (allGroups != null) {
Iterator<String> groupItr = allGroups.keySet().iterator();
final Iterator<String> groupItr = allGroups.keySet().iterator();
String groupName;
Integer groupCount = 0;
/*
* loop each group entry
* and read it's data.
@ -150,39 +220,35 @@ public class GlobalGroups {
groupCount++;
// Attempt to fetch the next group name.
groupName = groupItr.next();
} catch (Exception ex) {
} catch (final Exception ex) {
throw new IllegalArgumentException("Invalid group name for GlobalGroup entry (" + groupCount + ") in file: " + GlobalGroupsFile.getPath(), ex);
}
/*
* Create a new group with this name.
*/
Group newGroup = new Group(groupName.toLowerCase());
final Group newGroup = new Group(groupName.toLowerCase());
Object element;
// Permission nodes
try {
element = ((Map<String, Object>) allGroups.get(groupName)).get("permissions");
} catch (Exception ex) {
} catch (final Exception ex) {
throw new IllegalArgumentException("The GlobalGroup ' " + groupName + "' is formatted incorrectly: ", ex);
}
if (element != null)
if (element instanceof List) {
try {
for (String node : (List<String>) element) {
for (final String node : (List<String>) element) {
if ((node != null) && !node.isEmpty())
newGroup.addPermission(node);
}
} catch (ClassCastException ex) {
throw new IllegalArgumentException("Invalid permission node for global group: " + groupName, ex);
} catch (final ClassCastException ex) {
throw new IllegalArgumentException("不注册的权限节点 在全局组: " + groupName, ex);
}
} else if (element instanceof String) {
if ((element != null) && !((String) element).isEmpty())
newGroup.addPermission((String) element);
} else
throw new IllegalArgumentException("Unknown type of permission node for global group: " + groupName);
throw new IllegalArgumentException("未知的权限类型 在全局组: " + groupName);
// // Info nodes
// try {
// element = ((Map<String, Object>)allGroups.get(groupName)).get("info");
@ -199,42 +265,103 @@ public class GlobalGroups {
// newGroup.setVariables(vars);
// } else
// throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName);
// Push a new group
addGroup(newGroup);
}
}
removeGroupsChangedFlag();
}
setTimeStampGroups(GlobalGroupsFile.lastModified());
GroupManager.setLoaded(true);
// GlobalGroupsFile = null;
}
/**
* Creates a new group if it doesn't already exist.
*
* @param newGroup
*/
public Group newGroup(final Group newGroup) {
// Push a new group
if (!groups.containsKey(newGroup.getName().toLowerCase())) {
groups.put(newGroup.getName().toLowerCase(), newGroup);
this.setGroupsChanged(true);
return newGroup;
}
return null;
}
/**
* Delete a group if it exist.
*
* @param groupName
*/
public boolean removeGroup(final String groupName) {
// Push a new group
if (groups.containsKey(groupName.toLowerCase())) {
groups.remove(groupName.toLowerCase());
this.setGroupsChanged(true);
if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(groupName.toLowerCase(), GMGroupEvent.Action.GROUP_REMOVED);
return true;
}
return false;
}
/**
*
*/
public void removeGroupsChangedFlag() {
setGroupsChanged(false);
synchronized (groups) {
for (final Group g : groups.values()) {
g.flagAsSaved();
}
}
}
/**
* Returns a Set of all global group names.
*
* @return Set containing all group names.
*/
/*
* public Set<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
*/
public void writeGroups(boolean overwrite) {
public void writeGroups(final boolean overwrite) {
// File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml");
if (haveGroupsChanged()) {
if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) {
Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> groupsMap = new HashMap<String, Object>();
final Map<String, Object> root = new HashMap<String, Object>();
final Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap);
synchronized (groups) {
for (String groupKey : groups.keySet()) {
Group group = groups.get(groupKey);
for (final String groupKey : groups.keySet()) {
final Group group = groups.get(groupKey);
// Group header
Map<String, Object> aGroupMap = new HashMap<String, Object>();
final Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap);
// // Info nodes
// Map<String, Object> infoMap = new HashMap<String, Object>();
// aGroupMap.put("info", infoMap);
@ -242,20 +369,18 @@ public class GlobalGroups {
// for (String infoKey : group.getVariables().getVarKeyList()) {
// infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
// }
// Permission nodes
aGroupMap.put("permissions", group.getPermissionList());
}
}
if (!root.isEmpty()) {
DumperOptions opt = new DumperOptions();
final DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt);
try {
yaml.dump(root, new OutputStreamWriter(new FileOutputStream(GlobalGroupsFile), "UTF-8"));
} catch (UnsupportedEncodingException ex) {
} catch (FileNotFoundException ex) {
} catch (final UnsupportedEncodingException ex) {
} catch (final FileNotFoundException ex) {
}
}
setTimeStampGroups(GlobalGroupsFile.lastModified());
@ -274,210 +399,27 @@ public class GlobalGroups {
load();
}
}
}
/**
* Backup the BlobalGroups file
*
*
* @param w
*/
private void backupFile() {
File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
final File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
try {
Tasks.copy(GlobalGroupsFile, backupFile);
} catch (IOException ex) {
} catch (final IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
/**
* Adds a group, or replaces an existing one.
*
* @param groupToAdd
* @param timeStampGroups
* the timeStampGroups to set
*/
public void addGroup(Group groupToAdd) {
// Create a new group if it already exists
if (hasGroup(groupToAdd.getName())) {
groupToAdd = groupToAdd.clone();
removeGroup(groupToAdd.getName());
}
newGroup(groupToAdd);
haveGroupsChanged = true;
if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
protected void setTimeStampGroups(final long timeStampGroups) {
this.timeStampGroups = timeStampGroups;
}
/**
* Creates a new group if it doesn't already exist.
*
* @param newGroup
*/
public Group newGroup(Group newGroup) {
// Push a new group
if (!groups.containsKey(newGroup.getName().toLowerCase())) {
groups.put(newGroup.getName().toLowerCase(), newGroup);
this.setGroupsChanged(true);
return newGroup;
}
return null;
}
/**
* Delete a group if it exist.
*
* @param groupName
*/
public boolean removeGroup(String groupName) {
// Push a new group
if (groups.containsKey(groupName.toLowerCase())) {
groups.remove(groupName.toLowerCase());
this.setGroupsChanged(true);
if (GroupManager.isLoaded())
GroupManager.getGMEventHandler().callEvent(groupName.toLowerCase(), GMGroupEvent.Action.GROUP_REMOVED);
return true;
}
return false;
}
/**
* Returns true if the Global Group exists in the globalgroups.yml
*
* @param groupName
* @return true if the group exists
*/
public boolean hasGroup(String groupName) {
return groups.containsKey(groupName.toLowerCase());
}
/**
* Returns true if the group has the correct permission node.
*
* @param groupName
* @param permissionNode
* @return true if node exists
*/
public boolean hasPermission(String groupName, String permissionNode) {
if (!hasGroup(groupName))
return false;
return groups.get(groupName.toLowerCase()).hasSamePermissionNode(permissionNode);
}
/**
* Returns a PermissionCheckResult of the permission node for the group to
* be tested against.
*
* @param groupName
* @param permissionNode
* @return PermissionCheckResult object
*/
public PermissionCheckResult checkPermission(String groupName, String permissionNode) {
PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = permissionNode;
result.resultType = PermissionCheckResult.Type.NOTFOUND;
if (!hasGroup(groupName))
return result;
Group tempGroup = groups.get(groupName.toLowerCase());
if (tempGroup.hasSamePermissionNode(permissionNode))
result.resultType = PermissionCheckResult.Type.FOUND;
if (tempGroup.hasSamePermissionNode("-" + permissionNode))
result.resultType = PermissionCheckResult.Type.NEGATION;
if (tempGroup.hasSamePermissionNode("+" + permissionNode))
result.resultType = PermissionCheckResult.Type.EXCEPTION;
return result;
}
/**
* Returns a List of all permission nodes for this group null if none
*
* @param groupName
* @return List of all group names
*/
public List<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;
/*
*
*
* Created by ElgarL
*/
public class BukkitPermsUpdateTask implements Runnable {
public BukkitPermsUpdateTask() {
super();
}
@Override
public void run() {
// Signal loaded and update BukkitPermissions.
GroupManager.setLoaded(true);
GroupManager.BukkitPermissions.collectPermissions();
GroupManager.BukkitPermissions.updateAllPlayers();
GroupManager.logger.info("Bukkit Permissions Updated!");
GroupManager.logger.info("权限已更新!");
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,25 +9,24 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.anjocaido.groupmanager.data.User;
/**
*
*
* @author gabrielcouto
*/
public class OverloadedWorldHolder extends WorldDataHolder {
/**
*
*/
protected final Map<String, User> overloadedUsers = Collections.synchronizedMap(new HashMap<String, User>());
/**
*
*
* @param ph
*/
public OverloadedWorldHolder(WorldDataHolder ph) {
public OverloadedWorldHolder(final WorldDataHolder ph) {
super(ph.getName());
this.setGroupsFile(ph.getGroupsFile());
this.setUsersFile(ph.getUsersFile());
@ -36,30 +35,11 @@ public class OverloadedWorldHolder extends WorldDataHolder {
}
/**
*
* @param userName
* @return user object or a new user if none exists.
*/
@Override
public User getUser(String userName) {
// OVERLOADED CODE
String userNameLowered = userName.toLowerCase();
if (overloadedUsers.containsKey(userNameLowered)) {
return overloadedUsers.get(userNameLowered);
}
// END CODE
return super.getUser(userName);
}
/**
*
*
* @param theUser
*/
@Override
public void addUser(User theUser) {
if (theUser.getDataSource() != this) {
theUser = theUser.clone(this);
}
@ -82,13 +62,116 @@ public class OverloadedWorldHolder extends WorldDataHolder {
}
/**
*
*
* @param userName
* @return user object or a new user if none exists.
*/
@Override
public User getUser(final String userName) {
// OVERLOADED CODE
final String userNameLowered = userName.toLowerCase();
if (overloadedUsers.containsKey(userNameLowered)) {
return overloadedUsers.get(userNameLowered);
}
// END CODE
return super.getUser(userName);
}
/**
*
* @return Collection of all users
*/
@Override
public Collection<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
* @return true if removed/false if not found.
*/
@Override
public boolean removeUser(String userId) {
public boolean removeUser(final String userId) {
// OVERLOADED CODE
if (overloadedUsers.containsKey(userId.toLowerCase())) {
overloadedUsers.remove(userId.toLowerCase());
@ -103,118 +186,22 @@ public class OverloadedWorldHolder extends WorldDataHolder {
return false;
}
@Override
public boolean removeGroup(String groupName) {
if (groupName.equals(getDefaultGroup())) {
return false;
}
synchronized (getGroups()) {
for (String key : getGroups().keySet()) {
if (groupName.equalsIgnoreCase(key)) {
getGroups().remove(key);
synchronized (getUsers()) {
for (String userKey : getUsers().keySet()) {
User user = getUsers().get(userKey);
if (user.getGroupName().equalsIgnoreCase(key)) {
user.setGroup(getDefaultGroup());
}
}
}
// OVERLOADED CODE
synchronized (overloadedUsers) {
for (String userKey : overloadedUsers.keySet()) {
User user = overloadedUsers.get(userKey);
if (user.getGroupName().equalsIgnoreCase(key)) {
user.setGroup(getDefaultGroup());
}
}
}
// END OVERLOAD
setGroupsChanged(true);
return true;
}
}
}
return false;
}
/**
*
* @return Collection of all users
*/
@Override
public Collection<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.
* It doesn't affect permissions. But it enables plugins change the
* actual user permissions even in overload mode.
*
*
* @param userId
* @return user object
*/
public User surpassOverload(String userId) {
public User surpassOverload(final String userId) {
if (!isOverloaded(userId)) {
return getUser(userId);
}
if (getUsers().containsKey(userId.toLowerCase())) {
return getUsers().get(userId.toLowerCase());
}
User newUser = createUser(userId);
final User newUser = createUser(userId);
return newUser;
}
}

View File

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

View File

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

View File

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

View File

@ -6,61 +6,47 @@ import org.bukkit.event.HandlerList;
/**
* @author ElgarL
*
*
*/
public class GMSystemEvent extends Event {
/**
*
*/
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected Action action;
public GMSystemEvent(Action action) {
public GMSystemEvent(final Action action) {
super();
this.action = action;
}
public Action getAction() {
//////////////////////////////
public static HandlerList getHandlerList() {
return handlers;
}
public Action getAction() {
return this.action;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public void schedule(final GMSystemEvent event) {
synchronized (GroupManager.getGMEventHandler().getServer()) {
if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() {
@Override
public void run() {
GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event);
}
}, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event.");
}
}
public enum Action {
RELOADED,
SAVED,
DEFAULT_GROUP_CHANGED,
VALIDATE_TOGGLE,
}
public void schedule(final GMSystemEvent event) {
synchronized (GroupManager.getGMEventHandler().getServer()) {
if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() {
@Override
public void run() {
GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event);
}
}, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event.");
}
}
}

View File

@ -7,66 +7,62 @@ import org.bukkit.event.HandlerList;
/**
* @author ElgarL
*
*
*/
public class GMUserEvent extends Event {
/**
*
*/
private static final HandlerList handlers = new HandlerList();
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected User user;
protected String userName;
//////////////////////////////
protected Action action;
public GMUserEvent(User user, Action action) {
public GMUserEvent(final String userName, final Action action) {
super();
this.userName = userName;
this.action = action;
}
public GMUserEvent(final User user, final Action action) {
super();
this.user = user;
this.action = action;
this.userName = user.getLastName();
}
public GMUserEvent(String userName, Action action) {
super();
this.userName = userName;
this.action = action;
public static HandlerList getHandlerList() {
return handlers;
}
public Action getAction() {
return this.action;
}
public User getUser() {
@Override
public HandlerList getHandlers() {
return handlers;
}
public User getUser() {
return user;
}
public String getUserName() {
return userName;
}
public void schedule(final GMUserEvent event) {
synchronized (GroupManager.getGMEventHandler().getServer()) {
if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() {
@Override
public void run() {
GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event);
}
}, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event.");
}
}
public enum Action {
USER_PERMISSIONS_CHANGED,
USER_INHERITANCE_CHANGED,
@ -76,19 +72,4 @@ public class GMUserEvent extends Event {
USER_ADDED,
USER_REMOVED,
}
public void schedule(final GMUserEvent event) {
synchronized (GroupManager.getGMEventHandler().getServer()) {
if (GroupManager.getGMEventHandler().getServer().getScheduler().scheduleSyncDelayedTask(GroupManager.getGMEventHandler().getPlugin(), new Runnable() {
@Override
public void run() {
GroupManager.getGMEventHandler().getServer().getPluginManager().callEvent(event);
}
}, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event.");
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,18 +7,27 @@ package org.anjocaido.groupmanager.utils;
import java.util.Comparator;
/**
*
*
* @author gabrielcouto
*/
public class StringPermissionComparator implements Comparator<String> {
@Override
public int compare(String permA, String permB) {
private static StringPermissionComparator instance;
boolean ap = permA.startsWith("+");
boolean bp = permB.startsWith("+");
boolean am = permA.startsWith("-");
boolean bm = permB.startsWith("-");
public static StringPermissionComparator getInstance() {
if (instance == null) {
instance = new StringPermissionComparator();
}
return instance;
}
@Override
public int compare(final String permA, final String permB) {
final boolean ap = permA.startsWith("+");
final boolean bp = permB.startsWith("+");
final boolean am = permA.startsWith("-");
final boolean bm = permB.startsWith("-");
if (ap && bp) {
return 0;
}
@ -39,14 +48,4 @@ public class StringPermissionComparator implements Comparator<String> {
}
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;
/**
*
*
* @author gabrielcouto
*/
public abstract class Tasks {
/**
* Gets the exception stack trace as a string.
*
* @param exception
* @return stack trace as a string
* Appends a string to a file
*
* @param data
* @param file
*/
public static String getStackTraceAsString(Exception exception) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
return sw.toString();
public static void appendStringToFile(final String data, final String file) throws IOException {
final FileWriter outStream = new FileWriter("." + System.getProperty("file.separator") + file, true);
final BufferedWriter out = new BufferedWriter(outStream);
data.replaceAll("\n", System.getProperty("line.separator"));
out.append(new SimpleDateFormat("yyyy-MM-dd HH-mm").format(System.currentTimeMillis()));
out.append(System.getProperty("line.separator"));
out.append(data);
out.append(System.getProperty("line.separator"));
out.close();
}
public static void copy(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
public static void copy(final File src, final File dst) throws IOException {
final InputStream in = new FileInputStream(src);
copy(in, dst);
}
public static void copy(final InputStream src, final File dst) throws IOException {
final InputStream in = src;
final OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
final byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
@ -56,58 +62,12 @@ public abstract class Tasks {
out.close();
try {
in.close();
} catch (Exception e) {
}
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
copy(in, dst);
}
/**
* Appends a string to a file
*
* @param data
* @param file
*/
public static void appendStringToFile(String data, String file) throws IOException {
FileWriter outStream = new FileWriter("." + System.getProperty("file.separator") + file, true);
BufferedWriter out = new BufferedWriter(outStream);
data.replaceAll("\n", System.getProperty("line.separator"));
out.append(new SimpleDateFormat("yyyy-MM-dd HH-mm").format(System.currentTimeMillis()));
out.append(System.getProperty("line.separator"));
out.append(data);
out.append(System.getProperty("line.separator"));
out.close();
}
public static void removeOldFiles(GroupManager gm, File folder) {
if (folder.isDirectory()) {
long oldTime = System.currentTimeMillis() - (((long) gm.getGMConfig().getBackupDuration() * 60 * 60) * 1000);
for (File olds : folder.listFiles()) {
if (olds.isFile()) {
if (olds.lastModified() < oldTime) {
try {
olds.delete();
} catch (Exception e) {
}
}
}
}
} catch (final Exception e) {
}
}
public static String getDateString() {
GregorianCalendar now = new GregorianCalendar();
final GregorianCalendar now = new GregorianCalendar();
String date = "";
date += now.get(Calendar.DAY_OF_MONTH);
date += "-";
@ -117,38 +77,7 @@ public abstract class Tasks {
return date;
}
public static String getStringListInString(List<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 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) {
public static String getGroupListInString(final List<Group> list) {
if (list == null) {
return "";
}
@ -162,8 +91,48 @@ public abstract class Tasks {
return result;
}
public static String join(String[] arr, String separator) {
/**
* Gets the exception stack trace as a string.
*
* @param exception
* @return stack trace as a string
*/
public static String getStackTraceAsString(final Exception exception) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
return sw.toString();
}
public static String getStringArrayInString(final String[] list) {
if (list == null) {
return "";
}
String result = "";
for (int i = 0; i < list.length; i++) {
result += list[i];
if (i < ((list.length) - 1)) {
result += ", ";
}
}
return result;
}
public static String getStringListInString(final List<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)
return "";
String out = arr[0].toString();
@ -172,4 +141,20 @@ public abstract class Tasks {
return out;
}
public static void removeOldFiles(final GroupManager gm, final File folder) {
if (folder.isDirectory()) {
final long oldTime = System.currentTimeMillis() - (((long) gm.getGMConfig().getBackupDuration() * 60 * 60) * 1000);
for (final File olds : folder.listFiles()) {
if (olds.isFile()) {
if (olds.lastModified() < oldTime) {
try {
olds.delete();
} catch (final Exception e) {
}
}
}
}
}
}
}

View File

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