Merge remote branch 'remotes/origin/groupmanager'

This commit is contained in:
KHobbits 2012-04-15 19:41:06 +01:00
commit 26a0cd0761
29 changed files with 3724 additions and 3443 deletions

View file

@ -176,4 +176,7 @@ v 2.0:
- Fix 'manuadd' to use the default or selected world (via 'manselect'), if the world is not specified in the command. - Fix 'manuadd' to use the default or selected world (via 'manselect'), if the world is not specified in the command.
- Expand GlobalGroups.yml and groups.yml to cover the VanishNoPacket plugin. Demonstrating how to negate and add nodes when using the '*' permission with inheritance. - Expand GlobalGroups.yml and groups.yml to cover the VanishNoPacket plugin. Demonstrating how to negate and add nodes when using the '*' permission with inheritance.
- Fix silly nested throw/catch statements. Errors are now correctly generated when reading yml's. - Fix silly nested throw/catch statements. Errors are now correctly generated when reading yml's.
- Unregister the worldsHolder as a service on a reload/shutdown instead of the whole plugin. - Unregister the worldsHolder as a service on a reload/shutdown instead of the whole plugin.
- Update all code formatting to use tabs for indentation.
- Stop using our own deprecated methods as we tell others to do.
- Finally remove all deprecated methods.

View file

@ -13,81 +13,89 @@ import org.anjocaido.groupmanager.utils.Tasks;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class GMConfiguration { public class GMConfiguration {
private GroupManager plugin; private GroupManager plugin;
private File configFile; private File configFile;
private YamlConfiguration GMconfig; private YamlConfiguration GMconfig;
public GMConfiguration(GroupManager plugin) {
this.plugin = plugin;
load();
}
public void load() { public GMConfiguration(GroupManager plugin) {
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs();
}
configFile = new File(plugin.getDataFolder(), "config.yml");
if (!configFile.exists()) { this.plugin = plugin;
try { load();
Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile); }
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
GMconfig = new YamlConfiguration(); public void load() {
try {
GMconfig.load(configFile);
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex);
}
// Setup defaults
adjustLoggerLevel();
plugin.setValidateOnlinePlayer(isToggleValidate());
}
public boolean isOpOverride() {
return GMconfig.getBoolean("settings.config.opOverrides", true);
}
public boolean isToggleValidate() {
return GMconfig.getBoolean("settings.config.validate_toggle", true);
}
public Map<String, Object> getMirrorsMap() { if (!plugin.getDataFolder().exists()) {
// Try to fetch the old mirror path first plugin.getDataFolder().mkdirs();
}
configFile = new File(plugin.getDataFolder(), "config.yml");
if (!configFile.exists()) {
try {
Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
GMconfig = new YamlConfiguration();
try {
GMconfig.load(configFile);
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex);
}
// Setup defaults
adjustLoggerLevel();
plugin.setValidateOnlinePlayer(isToggleValidate());
}
public boolean isOpOverride() {
return GMconfig.getBoolean("settings.config.opOverrides", true);
}
public boolean isToggleValidate() {
return GMconfig.getBoolean("settings.config.validate_toggle", true);
}
public Map<String, Object> getMirrorsMap() {
// Try to fetch the old mirror path first
if (GMconfig.isConfigurationSection("settings.permission.world.mirror")) { if (GMconfig.isConfigurationSection("settings.permission.world.mirror")) {
return (Map<String, Object>) GMconfig.getConfigurationSection("settings.permission.world.mirror").getValues(false); return (Map<String, Object>) GMconfig.getConfigurationSection("settings.permission.world.mirror").getValues(false);
} else if (GMconfig.isConfigurationSection("settings.mirrors")){ } else if (GMconfig.isConfigurationSection("settings.mirrors")) {
return (Map<String, Object>) GMconfig.getConfigurationSection("settings.mirrors").getValues(false); return (Map<String, Object>) GMconfig.getConfigurationSection("settings.mirrors").getValues(false);
} }
return null; return null;
}
public Integer getSaveInterval() { }
return GMconfig.getInt("settings.data.save.minutes", 10);
}
public Integer getBackupDuration() {
return GMconfig.getInt("settings.data.save.hours", 24);
}
public void adjustLoggerLevel() { public Integer getSaveInterval() {
try { return GMconfig.getInt("settings.data.save.minutes", 10);
GroupManager.logger.setLevel(Level.parse(GMconfig.getString("settings.logging.level", "INFO"))); }
return;
} catch (Exception e) { public Integer getBackupDuration() {
}
return GMconfig.getInt("settings.data.save.hours", 24);
GroupManager.logger.setLevel(Level.INFO); }
}
public void adjustLoggerLevel() {
try {
GroupManager.logger.setLevel(Level.parse(GMconfig.getString("settings.logging.level", "INFO")));
return;
} catch (Exception e) {
}
GroupManager.logger.setLevel(Level.INFO);
}
} }

View file

@ -24,8 +24,6 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
/** /**
* @author ElgarL * @author ElgarL
* *
@ -42,6 +40,7 @@ public class GlobalGroups {
protected File GlobalGroupsFile = null; protected File GlobalGroupsFile = null;
public GlobalGroups(GroupManager plugin) { public GlobalGroups(GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
load(); load();
} }
@ -50,6 +49,7 @@ public class GlobalGroups {
* @return the haveGroupsChanged * @return the haveGroupsChanged
*/ */
public boolean haveGroupsChanged() { public boolean haveGroupsChanged() {
if (this.haveGroupsChanged) { if (this.haveGroupsChanged) {
return true; return true;
} }
@ -65,20 +65,24 @@ public class GlobalGroups {
* @return the timeStampGroups * @return the timeStampGroups
*/ */
public long getTimeStampGroups() { public long getTimeStampGroups() {
return timeStampGroups; return timeStampGroups;
} }
/** /**
* @param timeStampGroups the timeStampGroups to set * @param timeStampGroups the timeStampGroups to set
*/ */
protected void setTimeStampGroups(long timeStampGroups) { protected void setTimeStampGroups(long timeStampGroups) {
this.timeStampGroups = timeStampGroups; this.timeStampGroups = timeStampGroups;
} }
/** /**
* @param haveGroupsChanged * @param haveGroupsChanged
* the haveGroupsChanged to set * the haveGroupsChanged to set
*/ */
public void setGroupsChanged(boolean haveGroupsChanged) { public void setGroupsChanged(boolean haveGroupsChanged) {
this.haveGroupsChanged = haveGroupsChanged; this.haveGroupsChanged = haveGroupsChanged;
} }
@ -86,7 +90,7 @@ public class GlobalGroups {
public void load() { public void load() {
GGroups = new YamlConfiguration(); GGroups = new YamlConfiguration();
GroupManager.setLoaded(false); GroupManager.setLoaded(false);
// READ globalGroups FILE // READ globalGroups FILE
@ -110,44 +114,47 @@ public class GlobalGroups {
// Clear out old groups // Clear out old groups
resetGlobalGroups(); resetGlobalGroups();
if (!GGroups.getKeys(false).isEmpty()) { if (!GGroups.getKeys(false).isEmpty()) {
// Read all global groups // Read all global groups
Map<String, Object> allGroups = new HashMap<String, Object>(); Map<String, Object> allGroups = new HashMap<String, Object>();
try { try {
allGroups = (Map<String, Object>) GGroups.getConfigurationSection("groups").getValues(false); allGroups = (Map<String, Object>) GGroups.getConfigurationSection("groups").getValues(false);
} catch (Exception ex) { } catch (Exception ex) {
//ex.printStackTrace(); // ex.printStackTrace();
throw new IllegalArgumentException("Your " + GlobalGroupsFile.getPath() + " file is invalid. See console for details.", ex); throw new IllegalArgumentException("Your " + GlobalGroupsFile.getPath() + " file is invalid. See console for details.", ex);
} }
// Load each groups permissions list. // Load each groups permissions list.
if (allGroups != null) { if (allGroups != null) {
Iterator<String> groupItr = allGroups.keySet().iterator(); Iterator<String> groupItr = allGroups.keySet().iterator();
String groupName; String groupName;
Integer groupCount = 0; Integer groupCount = 0;
/* /*
* loop each group entry * loop each group entry
* and read it's data. * and read it's data.
*/ */
while (groupItr.hasNext()) { while (groupItr.hasNext()) {
try { try {
groupCount++; groupCount++;
// Attempt to fetch the next group name. // Attempt to fetch the next group name.
groupName = groupItr.next(); groupName = groupItr.next();
} catch (Exception ex) { } catch (Exception ex) {
throw new IllegalArgumentException("Invalid group name for GlobalGroup entry (" + groupCount + ") in file: " + GlobalGroupsFile.getPath(), ex); throw new IllegalArgumentException("Invalid group name for GlobalGroup entry (" + groupCount + ") in file: " + GlobalGroupsFile.getPath(), ex);
} }
Group newGroup = new Group(groupName.toLowerCase()); /*
* Create a new group with this name.
*/
Group newGroup = new Group(groupName.toLowerCase());
Object element; Object element;
// Permission nodes // Permission nodes
element = GGroups.get("groups." + groupName + ".permissions"); element = GGroups.get("groups." + groupName + ".permissions");
if (element != null) if (element != null)
if (element instanceof List) { if (element instanceof List) {
try { try {
@ -161,31 +168,31 @@ public class GlobalGroups {
newGroup.addPermission((String) element); newGroup.addPermission((String) element);
} else } else
throw new IllegalArgumentException("Unknown type of permission node for global group: " + groupName); throw new IllegalArgumentException("Unknown type of permission node for global group: " + groupName);
// Info nodes // Info nodes
element = GGroups.get("groups." + groupName + ".info"); element = GGroups.get("groups." + groupName + ".info");
if (element != null) if (element != null)
if (element instanceof MemorySection) { if (element instanceof MemorySection) {
Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> vars = new HashMap<String, Object>();
for (String key : ((MemorySection) element).getKeys(false)) { for (String key : ((MemorySection) element).getKeys(false)) {
vars.put(key, ((MemorySection) element).get(key)); vars.put(key, ((MemorySection) element).get(key));
} }
newGroup.setVariables(vars); newGroup.setVariables(vars);
} else } else
throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName); throw new IllegalArgumentException("Unknown type of info node for global group: " + groupName);
// Push a new group // Push a new group
addGroup(newGroup); addGroup(newGroup);
} }
} }
removeGroupsChangedFlag(); removeGroupsChangedFlag();
} }
setTimeStampGroups(GlobalGroupsFile.lastModified()); setTimeStampGroups(GlobalGroupsFile.lastModified());
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
//GlobalGroupsFile = null; // GlobalGroupsFile = null;
} }
/** /**
@ -194,33 +201,33 @@ public class GlobalGroups {
public void writeGroups(boolean overwrite) { public void writeGroups(boolean overwrite) {
//File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml"); // File GlobalGroupsFile = new File(plugin.getDataFolder(), "globalgroups.yml");
if (haveGroupsChanged()) { if (haveGroupsChanged()) {
if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) { if (overwrite || (!overwrite && (getTimeStampGroups() >= GlobalGroupsFile.lastModified()))) {
Map<String, Object> root = new HashMap<String, Object>(); Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> groupsMap = new HashMap<String, Object>(); Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap); root.put("groups", groupsMap);
for (String groupKey : groups.keySet()) { for (String groupKey : groups.keySet()) {
Group group = groups.get(groupKey); Group group = groups.get(groupKey);
// Group header // Group header
Map<String, Object> aGroupMap = new HashMap<String, Object>(); Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap); groupsMap.put(group.getName(), aGroupMap);
// Info nodes // Info nodes
Map<String, Object> infoMap = new HashMap<String, Object>(); Map<String, Object> infoMap = new HashMap<String, Object>();
aGroupMap.put("info", infoMap); aGroupMap.put("info", infoMap);
for (String infoKey : group.getVariables().getVarKeyList()) { for (String infoKey : group.getVariables().getVarKeyList()) {
infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
} }
// Permission nodes // Permission nodes
aGroupMap.put("permissions", group.getPermissionList()); aGroupMap.put("permissions", group.getPermissionList());
} }
if (!root.isEmpty()) { if (!root.isEmpty()) {
DumperOptions opt = new DumperOptions(); DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
@ -233,53 +240,55 @@ public class GlobalGroups {
} }
setTimeStampGroups(GlobalGroupsFile.lastModified()); setTimeStampGroups(GlobalGroupsFile.lastModified());
} else { } else {
// Newer file found. // Newer file found.
GroupManager.logger.log(Level.WARNING, "Newer GlobalGroups file found, but we have local changes!"); GroupManager.logger.log(Level.WARNING, "Newer GlobalGroups file found, but we have local changes!");
throw new IllegalStateException("Unable to save unless you issue a '/mansave force'"); throw new IllegalStateException("Unable to save unless you issue a '/mansave force'");
} }
removeGroupsChangedFlag(); removeGroupsChangedFlag();
} else { } else {
//Check for newer file as no local changes. // Check for newer file as no local changes.
if (getTimeStampGroups() < GlobalGroupsFile.lastModified()) { if (getTimeStampGroups() < GlobalGroupsFile.lastModified()) {
System.out.print("Newer GlobalGroups file found (Loading changes)!"); System.out.print("Newer GlobalGroups file found (Loading changes)!");
// Backup GlobalGroups file // Backup GlobalGroups file
backupFile(); backupFile();
load(); load();
} }
} }
} }
/** /**
* Backup the BlobalGroups file * Backup the BlobalGroups file
* @param w *
*/ * @param w
private void backupFile() { */
private void backupFile() {
File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
try { File backupFile = new File(plugin.getBackupFolder(), "bkp_ggroups_" + Tasks.getDateString() + ".yml");
Tasks.copy(GlobalGroupsFile, backupFile); try {
} catch (IOException ex) { Tasks.copy(GlobalGroupsFile, backupFile);
GroupManager.logger.log(Level.SEVERE, null, ex); } catch (IOException ex) {
} GroupManager.logger.log(Level.SEVERE, null, ex);
} }
}
/** /**
* Adds a group, or replaces an existing one. * Adds a group, or replaces an existing one.
* *
* @param groupToAdd * @param groupToAdd
*/ */
public void addGroup(Group groupToAdd) { public void addGroup(Group groupToAdd) {
// Create a new group if it already exists // Create a new group if it already exists
if (hasGroup(groupToAdd.getName())) { if (hasGroup(groupToAdd.getName())) {
groupToAdd = groupToAdd.clone(); groupToAdd = groupToAdd.clone();
removeGroup(groupToAdd.getName()); removeGroup(groupToAdd.getName());
} }
newGroup(groupToAdd); newGroup(groupToAdd);
haveGroupsChanged = true; haveGroupsChanged = true;
if (GroupManager.isLoaded()) if (GroupManager.isLoaded())
GroupManagerEventHandler.callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED); GroupManagerEventHandler.callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
} }
/** /**
@ -288,6 +297,7 @@ public class GlobalGroups {
* @param newGroup * @param newGroup
*/ */
public Group newGroup(Group newGroup) { public Group newGroup(Group newGroup) {
// Push a new group // Push a new group
if (!groups.containsKey(newGroup.getName().toLowerCase())) { if (!groups.containsKey(newGroup.getName().toLowerCase())) {
groups.put(newGroup.getName().toLowerCase(), newGroup); groups.put(newGroup.getName().toLowerCase(), newGroup);
@ -303,6 +313,7 @@ public class GlobalGroups {
* @param groupName * @param groupName
*/ */
public boolean removeGroup(String groupName) { public boolean removeGroup(String groupName) {
// Push a new group // Push a new group
if (groups.containsKey(groupName.toLowerCase())) { if (groups.containsKey(groupName.toLowerCase())) {
groups.remove(groupName.toLowerCase()); groups.remove(groupName.toLowerCase());
@ -321,6 +332,7 @@ public class GlobalGroups {
* @return true if the group exists * @return true if the group exists
*/ */
public boolean hasGroup(String groupName) { public boolean hasGroup(String groupName) {
return groups.containsKey(groupName.toLowerCase()); return groups.containsKey(groupName.toLowerCase());
} }
@ -376,6 +388,7 @@ public class GlobalGroups {
* @return List of all group names * @return List of all group names
*/ */
public List<String> getGroupsPermissions(String groupName) { public List<String> getGroupsPermissions(String groupName) {
if (!hasGroup(groupName)) if (!hasGroup(groupName))
return null; return null;
@ -388,6 +401,7 @@ public class GlobalGroups {
* @return Set containing all group names. * @return Set containing all group names.
*/ */
public Set<String> getGlobalGroups() { public Set<String> getGlobalGroups() {
return groups.keySet(); return groups.keySet();
} }
@ -395,14 +409,16 @@ public class GlobalGroups {
* Resets GlobalGroups. * Resets GlobalGroups.
*/ */
public void resetGlobalGroups() { public void resetGlobalGroups() {
this.groups = new HashMap<String, Group>(); this.groups = new HashMap<String, Group>();
} }
/** /**
* *
* @return a collection of the groups * @return a collection of the groups
*/ */
public Collection<Group> getGroupList() { public Collection<Group> getGroupList() {
return groups.values(); return groups.values();
} }
@ -413,6 +429,7 @@ public class GlobalGroups {
* @return Group object * @return Group object
*/ */
public Group getGroup(String groupName) { public Group getGroup(String groupName) {
if (!hasGroup(groupName)) if (!hasGroup(groupName))
return null; return null;
@ -424,17 +441,19 @@ public class GlobalGroups {
* @return the globalGroupsFile * @return the globalGroupsFile
*/ */
public File getGlobalGroupsFile() { public File getGlobalGroupsFile() {
return GlobalGroupsFile; return GlobalGroupsFile;
} }
/** /**
* *
*/ */
public void removeGroupsChangedFlag() { public void removeGroupsChangedFlag() {
setGroupsChanged(false);
for (Group g : groups.values()) { setGroupsChanged(false);
g.flagAsSaved(); for (Group g : groups.values()) {
} g.flagAsSaved();
} }
}
} }

View file

@ -5,24 +5,25 @@ import org.anjocaido.groupmanager.GroupManager;
/* /*
* *
* Created by ElgarL * Created by ElgarL
*
*/ */
public class BukkitPermsUpdateTask implements Runnable { public class BukkitPermsUpdateTask implements Runnable {
public BukkitPermsUpdateTask() { public BukkitPermsUpdateTask() {
super();
super();
} }
@Override @Override
public void run() { public void run() {
// Signal loaded and update BukkitPermissions. // Signal loaded and update BukkitPermissions.
GroupManager.setLoaded(true); GroupManager.setLoaded(true);
GroupManager.BukkitPermissions.collectPermissions(); GroupManager.BukkitPermissions.collectPermissions();
GroupManager.BukkitPermissions.updateAllPlayers(); GroupManager.BukkitPermissions.updateAllPlayers();
GroupManager.logger.info("Bukkit Permissions Updated!"); GroupManager.logger.info("Bukkit Permissions Updated!");
} }
} }

View file

@ -13,151 +13,169 @@ import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.utils.StringPermissionComparator; import org.anjocaido.groupmanager.utils.StringPermissionComparator;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class DataUnit { public abstract class DataUnit {
private WorldDataHolder dataSource; private WorldDataHolder dataSource;
private String name; private String name;
private boolean changed, sorted = false; private boolean changed, sorted = false;
private ArrayList<String> permissions = new ArrayList<String>(); private ArrayList<String> permissions = new ArrayList<String>();
public DataUnit(WorldDataHolder dataSource, String name) { public DataUnit(WorldDataHolder dataSource, String name) {
this.dataSource = dataSource;
this.name = name;
}
public DataUnit(String name) { this.dataSource = dataSource;
this.name = name; this.name = name;
}
public DataUnit(String name) {
this.name = name;
} }
/** /**
* Every group is matched only by their names and DataSources names. * Every group is matched only by their names and DataSources names.
* @param o *
* @return true if they are equal. false if not. * @param o
*/ * @return true if they are equal. false if not.
@Override */
public boolean equals(Object o) { @Override
if (o instanceof DataUnit) { public boolean equals(Object o) {
DataUnit go = (DataUnit) o;
if (this.getName().equalsIgnoreCase(go.getName())) {
// Global Group match.
if (this.dataSource == null && go.getDataSource() == null)
return true;
// This is a global group, the object to test isn't.
if (this.dataSource == null && go.getDataSource() != null)
return false;
// This is not a global group, but the object to test is.
if (this.dataSource != null && go.getDataSource() == null)
return false;
// Match on group name and world name.
if (this.dataSource.getName().equalsIgnoreCase(go.getDataSource().getName()))
return true;
}
}
return false;
}
@Override if (o instanceof DataUnit) {
public int hashCode() { DataUnit go = (DataUnit) o;
int hash = 5; if (this.getName().equalsIgnoreCase(go.getName())) {
hash = 71 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0); // Global Group match.
return hash; if (this.dataSource == null && go.getDataSource() == null)
} return true;
// This is a global group, the object to test isn't.
/** if (this.dataSource == null && go.getDataSource() != null)
* Set the data source to point to a different worldDataHolder return false;
* // This is not a global group, but the object to test is.
* @param source if (this.dataSource != null && go.getDataSource() == null)
*/ return false;
public void setDataSource(WorldDataHolder source) { // Match on group name and world name.
this.dataSource = source; if (this.dataSource.getName().equalsIgnoreCase(go.getDataSource().getName()))
} return true;
}
}
return false;
}
/** @Override
* Get the current worldDataHolder this object is pointing to public int hashCode() {
*
* @return the dataSource
*/
public WorldDataHolder getDataSource() {
return dataSource;
}
/** int hash = 5;
* @return the name hash = 71 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0);
*/ return hash;
public String getName() { }
return name;
}
public void flagAsChanged() { /**
WorldDataHolder testSource = getDataSource(); * Set the data source to point to a different worldDataHolder
String source = ""; *
* @param source
if (testSource == null) */
source = "GlobalGroups"; public void setDataSource(WorldDataHolder source) {
else
source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getName() + " flagged as changed!");
// for(StackTraceElement st: Thread.currentThread().getStackTrace()){
// GroupManager.logger.finest(st.toString());
// }
sorted = false;
changed = true;
}
public boolean isChanged() { this.dataSource = source;
return changed; }
}
public void flagAsSaved() { /**
WorldDataHolder testSource = getDataSource(); * Get the current worldDataHolder this object is pointing to
String source = ""; *
* @return the dataSource
if (testSource == null) */
source = "GlobalGroups"; public WorldDataHolder getDataSource() {
else
source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getName() + " flagged as saved!");
changed = false;
}
public boolean hasSamePermissionNode(String permission) { return dataSource;
return permissions.contains(permission); }
}
public void addPermission(String permission) { /**
if (!hasSamePermissionNode(permission)) { * @return the name
permissions.add(permission); */
} public String getName() {
flagAsChanged();
}
public boolean removePermission(String permission) { return name;
flagAsChanged(); }
return permissions.remove(permission);
}
/** public void flagAsChanged() {
* 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() {
return Collections.unmodifiableList(permissions);
}
public boolean isSorted() {
return this.sorted;
}
public void sortPermissions() { WorldDataHolder testSource = getDataSource();
if (!isSorted()) { String source = "";
Collections.sort(permissions, StringPermissionComparator.getInstance());
sorted = true; if (testSource == null)
} source = "GlobalGroups";
} else
source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getName() + " flagged as changed!");
// for(StackTraceElement st: Thread.currentThread().getStackTrace()){
// GroupManager.logger.finest(st.toString());
// }
sorted = false;
changed = true;
}
public boolean isChanged() {
return changed;
}
public void flagAsSaved() {
WorldDataHolder testSource = getDataSource();
String source = "";
if (testSource == null)
source = "GlobalGroups";
else
source = testSource.getName();
GroupManager.logger.finest("DataSource: " + source + " - DataUnit: " + getName() + " flagged as saved!");
changed = false;
}
public boolean hasSamePermissionNode(String permission) {
return permissions.contains(permission);
}
public void addPermission(String permission) {
if (!hasSamePermissionNode(permission)) {
permissions.add(permission);
}
flagAsChanged();
}
public boolean removePermission(String permission) {
flagAsChanged();
return permissions.remove(permission);
}
/**
* 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() {
return Collections.unmodifiableList(permissions);
}
public boolean isSorted() {
return this.sorted;
}
public void sortPermissions() {
if (!isSorted()) {
Collections.sort(permissions, StringPermissionComparator.getInstance());
sorted = true;
}
}
} }

View file

@ -15,160 +15,173 @@ import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* *
* @author gabrielcouto/ElgarL * @author gabrielcouto/ElgarL
*/ */
public class Group extends DataUnit implements Cloneable { public class Group extends DataUnit implements Cloneable {
/** /**
* The group it inherits DIRECTLY! * The group it inherits DIRECTLY!
*/ */
private ArrayList<String> inherits = new ArrayList<String>(); private ArrayList<String> inherits = new ArrayList<String>();
/** /**
*This one holds the fields in INFO node. * This one holds the fields in INFO node.
* like prefix = 'c' * like prefix = 'c'
* or build = false * or build = false
*/ */
private GroupVariables variables = new GroupVariables(this); private GroupVariables variables = new GroupVariables(this);
/** /**
* Constructor for individual World Groups. * Constructor for individual World Groups.
* *
* @param name * @param name
*/ */
public Group(WorldDataHolder source, String name) { public Group(WorldDataHolder source, String name) {
super(source, name);
}
/**
* Constructor for Global Groups.
*
* @param name
*/
public Group(String name) {
super(name);
}
/**
* Is this a GlobalGroup
*
* @return true if this is a global group
*/
public boolean isGlobal() {
return (getDataSource() == null);
}
/**
* Clone this group
* @return a clone of this group
*/
@Override
public Group clone() {
Group clone;
if (isGlobal()) {
clone = new Group(this.getName());
} else {
clone = new Group(getDataSource(), this.getName());
clone.inherits = new ArrayList<String>(this.getInherits());
}
for (String perm : this.getPermissionList()) {
clone.addPermission(perm);
}
clone.variables = ((GroupVariables) variables).clone(clone);
//clone.flagAsChanged();
return clone;
}
/** super(source, name);
* Use this to deliver a group from a different dataSource to another }
* @param dataSource
* @return Null or Clone
*/
public Group clone(WorldDataHolder dataSource) {
if (dataSource.groupExists(this.getName())) {
return null;
}
Group clone = dataSource.createGroup(this.getName());
// Don't add inheritance for GlobalGroups
if (!isGlobal()) {
clone.inherits = new ArrayList<String>(this.getInherits());
}
for (String perm : this.getPermissionList()) {
clone.addPermission(perm);
}
clone.variables = variables.clone(clone);
clone.flagAsChanged(); //use this to make the new dataSource save the new group
return clone;
}
/** /**
* an unmodifiable list of inherits list * Constructor for Global Groups.
* You can't manage the list by here *
* Lol... version 0.6 had a problem because this. * @param name
* @return the inherits */
*/ public Group(String name) {
public List<String> getInherits() {
return Collections.unmodifiableList(inherits);
}
/** super(name);
* @param inherit the inherits to set }
*/
public void addInherits(Group inherit) {
if (!isGlobal()) {
if (!this.getDataSource().groupExists(inherit.getName())) {
getDataSource().addGroup(inherit);
}
if (!inherits.contains(inherit.getName().toLowerCase())) {
inherits.add(inherit.getName().toLowerCase());
}
flagAsChanged();
if (GroupManager.isLoaded()) {
GroupManager.BukkitPermissions.updateAllPlayers();
GroupManagerEventHandler.callEvent(this, Action.GROUP_INHERITANCE_CHANGED);
}
}
}
public boolean removeInherits(String inherit) { /**
if (!isGlobal()) { * Is this a GlobalGroup
if (this.inherits.contains(inherit.toLowerCase())) { *
this.inherits.remove(inherit.toLowerCase()); * @return true if this is a global group
flagAsChanged(); */
GroupManagerEventHandler.callEvent(this, Action.GROUP_INHERITANCE_CHANGED); public boolean isGlobal() {
return true;
}
}
return false;
}
/** return (getDataSource() == null);
* @return the variables }
*/
public GroupVariables getVariables() {
return variables;
}
/** /**
* * Clone this group
* @param varList *
*/ * @return a clone of this group
public void setVariables(Map<String, Object> varList) { */
if (!isGlobal()) { @Override
GroupVariables temp = new GroupVariables(this, varList); public Group clone() {
variables.clearVars();
for (String key : temp.getVarKeyList()) { Group clone;
variables.addVar(key, temp.getVarObject(key));
} if (isGlobal()) {
flagAsChanged(); clone = new Group(this.getName());
if (GroupManager.isLoaded()) { } else {
GroupManager.BukkitPermissions.updateAllPlayers(); clone = new Group(getDataSource(), this.getName());
GroupManagerEventHandler.callEvent(this, Action.GROUP_INFO_CHANGED); clone.inherits = new ArrayList<String>(this.getInherits());
} }
}
} for (String perm : this.getPermissionList()) {
clone.addPermission(perm);
}
clone.variables = ((GroupVariables) variables).clone(clone);
//clone.flagAsChanged();
return clone;
}
/**
* Use this to deliver a group from a different dataSource to another
*
* @param dataSource
* @return Null or Clone
*/
public Group clone(WorldDataHolder dataSource) {
if (dataSource.groupExists(this.getName())) {
return null;
}
Group clone = dataSource.createGroup(this.getName());
// Don't add inheritance for GlobalGroups
if (!isGlobal()) {
clone.inherits = new ArrayList<String>(this.getInherits());
}
for (String perm : this.getPermissionList()) {
clone.addPermission(perm);
}
clone.variables = variables.clone(clone);
clone.flagAsChanged(); //use this to make the new dataSource save the new group
return clone;
}
/**
* an unmodifiable list of inherits list
* You can't manage the list by here
* Lol... version 0.6 had a problem because this.
*
* @return the inherits
*/
public List<String> getInherits() {
return Collections.unmodifiableList(inherits);
}
/**
* @param inherit the inherits to set
*/
public void addInherits(Group inherit) {
if (!isGlobal()) {
if (!this.getDataSource().groupExists(inherit.getName())) {
getDataSource().addGroup(inherit);
}
if (!inherits.contains(inherit.getName().toLowerCase())) {
inherits.add(inherit.getName().toLowerCase());
}
flagAsChanged();
if (GroupManager.isLoaded()) {
GroupManager.BukkitPermissions.updateAllPlayers();
GroupManagerEventHandler.callEvent(this, Action.GROUP_INHERITANCE_CHANGED);
}
}
}
public boolean removeInherits(String inherit) {
if (!isGlobal()) {
if (this.inherits.contains(inherit.toLowerCase())) {
this.inherits.remove(inherit.toLowerCase());
flagAsChanged();
GroupManagerEventHandler.callEvent(this, Action.GROUP_INHERITANCE_CHANGED);
return true;
}
}
return false;
}
/**
* @return the variables
*/
public GroupVariables getVariables() {
return variables;
}
/**
*
* @param varList
*/
public void setVariables(Map<String, Object> varList) {
if (!isGlobal()) {
GroupVariables temp = new GroupVariables(this, varList);
variables.clearVars();
for (String key : temp.getVarKeyList()) {
variables.addVar(key, temp.getVarObject(key));
}
flagAsChanged();
if (GroupManager.isLoaded()) {
GroupManager.BukkitPermissions.updateAllPlayers();
GroupManagerEventHandler.callEvent(this, Action.GROUP_INFO_CHANGED);
}
}
}
} }

View file

@ -7,81 +7,88 @@ package org.anjocaido.groupmanager.data;
import java.util.Map; import java.util.Map;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class GroupVariables extends Variables implements Cloneable { public class GroupVariables extends Variables implements Cloneable {
private Group owner; private Group owner;
public GroupVariables(Group owner) { public GroupVariables(Group owner) {
super(owner);
this.owner = owner;
addVar("prefix", "");
addVar("suffix", "");
addVar("build", false);
}
public GroupVariables(Group owner, Map<String, Object> varList) { super(owner);
super(owner); this.owner = owner;
variables = varList; addVar("prefix", "");
if (variables.get("prefix") == null) { addVar("suffix", "");
variables.put("prefix", ""); addVar("build", false);
owner.flagAsChanged(); }
}
//thisGrp.prefix = infoNode.get("prefix").toString();
if (variables.get("suffix") == null) { public GroupVariables(Group owner, Map<String, Object> varList) {
variables.put("suffix", "");
owner.flagAsChanged();
}
//thisGrp.suffix = infoNode.get("suffix").toString();
if (variables.get("build") == null) { super(owner);
variables.put("build", false); variables = varList;
owner.flagAsChanged(); if (variables.get("prefix") == null) {
} variables.put("prefix", "");
this.owner = owner; owner.flagAsChanged();
} }
//thisGrp.prefix = infoNode.get("prefix").toString();
/** if (variables.get("suffix") == null) {
* A clone of all vars here. variables.put("suffix", "");
* @return GroupVariables clone owner.flagAsChanged();
*/ }
protected GroupVariables clone(Group newOwner) { //thisGrp.suffix = infoNode.get("suffix").toString();
GroupVariables clone = new GroupVariables(newOwner);
for (String key : variables.keySet()) {
clone.variables.put(key, variables.get(key));
}
newOwner.flagAsChanged();
return clone;
}
/** if (variables.get("build") == null) {
* Remove a var from the list variables.put("build", false);
* @param name owner.flagAsChanged();
*/ }
@Override this.owner = owner;
public void removeVar(String name) { }
try {
this.variables.remove(name);
} catch (Exception e) {
}
if (name.equals("prefix")) {
addVar("prefix", "");
} else if (name.equals("suffix")) {
addVar("suffix", "");
} else if (name.equals("build")) {
addVar("build", false);
}
owner.flagAsChanged();
}
/** /**
* @return the owner * A clone of all vars here.
*/ *
@Override * @return GroupVariables clone
public Group getOwner() { */
return owner; protected GroupVariables clone(Group newOwner) {
}
GroupVariables clone = new GroupVariables(newOwner);
for (String key : variables.keySet()) {
clone.variables.put(key, variables.get(key));
}
newOwner.flagAsChanged();
return clone;
}
/**
* Remove a var from the list
*
* @param name
*/
@Override
public void removeVar(String name) {
try {
this.variables.remove(name);
} catch (Exception e) {
}
if (name.equals("prefix")) {
addVar("prefix", "");
} else if (name.equals("suffix")) {
addVar("suffix", "");
} else if (name.equals("build")) {
addVar("build", false);
}
owner.flagAsChanged();
}
/**
* @return the owner
*/
@Override
public Group getOwner() {
return owner;
}
} }

View file

@ -16,7 +16,6 @@ import java.util.Map;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
/** /**
* *
* @author gabrielcouto/ElgarL * @author gabrielcouto/ElgarL
@ -40,6 +39,7 @@ public class User extends DataUnit implements Cloneable {
* @param name * @param name
*/ */
public User(WorldDataHolder source, String name) { public User(WorldDataHolder source, String name) {
super(source, name); super(source, name);
this.group = source.getDefaultGroup().getName(); this.group = source.getDefaultGroup().getName();
} }
@ -50,6 +50,7 @@ public class User extends DataUnit implements Cloneable {
*/ */
@Override @Override
public User clone() { public User clone() {
User clone = new User(getDataSource(), this.getName()); User clone = new User(getDataSource(), this.getName());
clone.group = this.group; clone.group = this.group;
for (String perm : this.getPermissionList()) { for (String perm : this.getPermissionList()) {
@ -67,6 +68,7 @@ public class User extends DataUnit implements Cloneable {
* @return null if given dataSource already contains the same user * @return null if given dataSource already contains the same user
*/ */
public User clone(WorldDataHolder dataSource) { public User clone(WorldDataHolder dataSource) {
if (dataSource.isUserDeclared(this.getName())) { if (dataSource.isUserDeclared(this.getName())) {
return null; return null;
} }
@ -85,6 +87,7 @@ public class User extends DataUnit implements Cloneable {
} }
public Group getGroup() { public Group getGroup() {
Group result = getDataSource().getGroup(group); Group result = getDataSource().getGroup(group);
if (result == null) { if (result == null) {
this.setGroup(getDataSource().getDefaultGroup()); this.setGroup(getDataSource().getDefaultGroup());
@ -97,6 +100,7 @@ public class User extends DataUnit implements Cloneable {
* @return the group * @return the group
*/ */
public String getGroupName() { public String getGroupName() {
Group result = getDataSource().getGroup(group); Group result = getDataSource().getGroup(group);
if (result == null) { if (result == null) {
group = getDataSource().getDefaultGroup().getName(); group = getDataSource().getDefaultGroup().getName();
@ -104,33 +108,23 @@ public class User extends DataUnit implements Cloneable {
return group; return group;
} }
/**
* @param group
* the group to set
*/
@Deprecated
public void setGroup(String group) {
this.group = group;
flagAsChanged();
if (GroupManager.isLoaded())
if (!GroupManager.BukkitPermissions.isPlayer_join())
GroupManager.BukkitPermissions.updatePlayer(getBukkitPlayer());
}
/** /**
* @param group * @param group
* the group to set * the group to set
*/ */
public void setGroup(Group group) { public void setGroup(Group group) {
setGroup(group, true); setGroup(group, true);
} }
/** /**
* @param group the group to set * @param group the group to set
* @param updatePerms if we are to trigger a superperms update. * @param updatePerms if we are to trigger a superperms update.
* *
*/ */
public void setGroup(Group group, Boolean updatePerms) { public void setGroup(Group group, Boolean updatePerms) {
if (!this.getDataSource().groupExists(group.getName())) { if (!this.getDataSource().groupExists(group.getName())) {
getDataSource().addGroup(group); getDataSource().addGroup(group);
} }
@ -151,12 +145,13 @@ public class User extends DataUnit implements Cloneable {
if (notify) if (notify)
GroupManager.notify(this.getName(), String.format(" moved to the group %s.", group.getName())); GroupManager.notify(this.getName(), String.format(" moved to the group %s.", group.getName()));
GroupManagerEventHandler.callEvent(this, Action.USER_GROUP_CHANGED); GroupManagerEventHandler.callEvent(this, Action.USER_GROUP_CHANGED);
} }
} }
public boolean addSubGroup(Group subGroup) { public boolean addSubGroup(Group subGroup) {
// Don't allow adding a subgroup if it's already set as the primary. // Don't allow adding a subgroup if it's already set as the primary.
if (this.group.equalsIgnoreCase(subGroup.getName())) { if (this.group.equalsIgnoreCase(subGroup.getName())) {
return false; return false;
@ -164,12 +159,12 @@ public class User extends DataUnit implements Cloneable {
// User already has this subgroup // User already has this subgroup
if (containsSubGroup(subGroup)) if (containsSubGroup(subGroup))
return false; return false;
// If the group doesn't exists add it // If the group doesn't exists add it
if (!this.getDataSource().groupExists(subGroup.getName())) { if (!this.getDataSource().groupExists(subGroup.getName())) {
getDataSource().addGroup(subGroup); getDataSource().addGroup(subGroup);
} }
subGroups.add(subGroup.getName()); subGroups.add(subGroup.getName());
flagAsChanged(); flagAsChanged();
if (GroupManager.isLoaded()) { if (GroupManager.isLoaded()) {
@ -178,25 +173,29 @@ public class User extends DataUnit implements Cloneable {
GroupManagerEventHandler.callEvent(this, Action.USER_SUBGROUP_CHANGED); GroupManagerEventHandler.callEvent(this, Action.USER_SUBGROUP_CHANGED);
} }
return true; return true;
//subGroup = getDataSource().getGroup(subGroup.getName()); //subGroup = getDataSource().getGroup(subGroup.getName());
//removeSubGroup(subGroup); //removeSubGroup(subGroup);
//subGroups.add(subGroup.getName()); //subGroups.add(subGroup.getName());
} }
public int subGroupsSize() { public int subGroupsSize() {
return subGroups.size(); return subGroups.size();
} }
public boolean isSubGroupsEmpty() { public boolean isSubGroupsEmpty() {
return subGroups.isEmpty(); return subGroups.isEmpty();
} }
public boolean containsSubGroup(Group subGroup) { public boolean containsSubGroup(Group subGroup) {
return subGroups.contains(subGroup.getName()); return subGroups.contains(subGroup.getName());
} }
public boolean removeSubGroup(Group subGroup) { public boolean removeSubGroup(Group subGroup) {
try { try {
if (subGroups.remove(subGroup.getName())) { if (subGroups.remove(subGroup.getName())) {
flagAsChanged(); flagAsChanged();
@ -212,6 +211,7 @@ public class User extends DataUnit implements Cloneable {
} }
public ArrayList<Group> subGroupListCopy() { public ArrayList<Group> subGroupListCopy() {
ArrayList<Group> val = new ArrayList<Group>(); ArrayList<Group> val = new ArrayList<Group>();
for (String gstr : subGroups) { for (String gstr : subGroups) {
Group g = getDataSource().getGroup(gstr); Group g = getDataSource().getGroup(gstr);
@ -225,6 +225,7 @@ public class User extends DataUnit implements Cloneable {
} }
public ArrayList<String> subGroupListStringCopy() { public ArrayList<String> subGroupListStringCopy() {
return new ArrayList<String>(subGroups); return new ArrayList<String>(subGroups);
} }
@ -232,6 +233,7 @@ public class User extends DataUnit implements Cloneable {
* @return the variables * @return the variables
*/ */
public UserVariables getVariables() { public UserVariables getVariables() {
return variables; return variables;
} }
@ -240,6 +242,7 @@ public class User extends DataUnit implements Cloneable {
* @param varList * @param varList
*/ */
public void setVariables(Map<String, Object> varList) { public void setVariables(Map<String, Object> varList) {
//UserVariables temp = new UserVariables(this, varList); //UserVariables temp = new UserVariables(this, varList);
variables.clearVars(); variables.clearVars();
for (String key : varList.keySet()) { for (String key : varList.keySet()) {
@ -254,6 +257,7 @@ public class User extends DataUnit implements Cloneable {
} }
public User updatePlayer(Player player) { public User updatePlayer(Player player) {
if (player != null) { if (player != null) {
bukkitPlayer = player; bukkitPlayer = player;
} }
@ -261,6 +265,7 @@ public class User extends DataUnit implements Cloneable {
} }
public Player getBukkitPlayer() { public Player getBukkitPlayer() {
if (bukkitPlayer == null) { if (bukkitPlayer == null) {
bukkitPlayer = Bukkit.getPlayer(this.getName()); bukkitPlayer = Bukkit.getPlayer(this.getName());
} }

View file

@ -7,42 +7,47 @@ package org.anjocaido.groupmanager.data;
import java.util.Map; import java.util.Map;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class UserVariables extends Variables { public class UserVariables extends Variables {
private User owner; private User owner;
public UserVariables(User owner) { public UserVariables(User owner) {
super(owner);
this.owner = owner;
}
public UserVariables(User owner, Map<String, Object> varList) { super(owner);
super(owner); this.owner = owner;
this.variables = varList; }
this.owner = owner;
}
/** public UserVariables(User owner, Map<String, Object> varList) {
* A clone of all vars here.
* @return UserVariables clone
*/
protected UserVariables clone(User newOwner) {
UserVariables clone = new UserVariables(newOwner);
for (String key : variables.keySet()) {
clone.variables.put(key, variables.get(key));
}
newOwner.flagAsChanged();
return clone;
}
/** super(owner);
* @return the owner this.variables = varList;
*/ this.owner = owner;
@Override }
public User getOwner() {
return owner; /**
} * A clone of all vars here.
*
* @return UserVariables clone
*/
protected UserVariables clone(User newOwner) {
UserVariables clone = new UserVariables(newOwner);
for (String key : variables.keySet()) {
clone.variables.put(key, variables.get(key));
}
newOwner.flagAsChanged();
return clone;
}
/**
* @return the owner
*/
@Override
public User getOwner() {
return owner;
}
} }

View file

@ -9,178 +9,200 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
*A class that holds variables of a user/group. * A class that holds variables of a user/group.
* In groups, it holds the contents of INFO node. * In groups, it holds the contents of INFO node.
* Like: * Like:
* prefix * prefix
* suffix * suffix
* build * build
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class Variables implements Cloneable { public abstract class Variables implements Cloneable {
private DataUnit owner; private DataUnit owner;
protected Map<String, Object> variables = new HashMap<String, Object>(); protected Map<String, Object> variables = new HashMap<String, Object>();
public Variables(DataUnit owner) { public Variables(DataUnit owner) {
this.owner = owner;
}
/** this.owner = owner;
* 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) {
if (o == null) {
return;
}
if (variables.containsKey(name)) {
variables.remove(name);
}
variables.put(name, o);
owner.flagAsChanged();
}
/** /**
* Returns the object inside the var * Add var to the the INFO node.
* @param name * examples:
* @return a Object if exists. null if doesn't exists * addVar("build",true);
*/ * addVar("prefix","c");
public Object getVarObject(String name) { *
return variables.get(name); * @param name key name of the var
} * @param o the object value of the var
*/
public void addVar(String name, Object o) {
/** if (o == null) {
* Get the String value for the given var name return;
* @param name the var key name }
* @return "" if null. or the toString() value of object if (variables.containsKey(name)) {
*/ variables.remove(name);
public String getVarString(String name) { }
Object o = variables.get(name); variables.put(name, o);
try { owner.flagAsChanged();
return o == null ? "" : o.toString(); }
} catch (Exception e) {
return "";
}
}
/** /**
* * Returns the object inside the var
* @param name *
* @return false if null. or a Boolean.parseBoolean of the string * @param name
*/ * @return a Object if exists. null if doesn't exists
public Boolean getVarBoolean(String name) { */
Object o = variables.get(name); public Object getVarObject(String name) {
try {
return o == null ? false : Boolean.parseBoolean(o.toString());
} catch (Exception e) {
return false;
}
}
/** return variables.get(name);
* }
* @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;
}
}
/** /**
* * Get the String value for the given var name
* @param name *
* @return -1 if null. or a parseDouble of the string * @param name the var key name
*/ * @return "" if null. or the toString() value of object
public Double getVarDouble(String name) { */
Object o = variables.get(name); public String getVarString(String name) {
try {
return o == null ? -1.0D : Double.parseDouble(o.toString());
} catch (Exception e) {
return -1.0D;
}
}
/** Object o = variables.get(name);
* All variable keys this is holding try {
* @return Set of all variable names. return o == null ? "" : o.toString();
*/ } catch (Exception e) {
public Set<String> getVarKeyList() { return "";
return variables.keySet(); }
} }
/** /**
* verify is a var exists *
* @param name the key name of the var * @param name
* @return true if that var exists * @return false if null. or a Boolean.parseBoolean of the string
*/ */
public boolean hasVar(String name) { public Boolean getVarBoolean(String name) {
return variables.containsKey(name);
}
/** Object o = variables.get(name);
* Returns the quantity of vars this is holding try {
* @return the number of vars return o == null ? false : Boolean.parseBoolean(o.toString());
*/ } catch (Exception e) {
public int getSize() { return false;
return variables.size(); }
} }
/** /**
* Remove a var from the list *
* @param name * @param name
*/ * @return -1 if null. or a parseInt of the string
public void removeVar(String name) { */
try { public Integer getVarInteger(String name) {
variables.remove(name);
} catch (Exception e) {
}
owner.flagAsChanged();
}
public static Object parseVariableValue(String value) { Object o = variables.get(name);
try { try {
Integer i = Integer.parseInt(value); return o == null ? -1 : Integer.parseInt(o.toString());
return i; } catch (Exception e) {
} catch (NumberFormatException e) { return -1;
} }
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;
} /**
*
* @param name
* @return -1 if null. or a parseDouble of the string
*/
public Double getVarDouble(String name) {
public void clearVars() { Object o = variables.get(name);
variables.clear(); try {
owner.flagAsChanged(); return o == null ? -1.0D : Double.parseDouble(o.toString());
} } catch (Exception e) {
return -1.0D;
}
}
/** /**
* @return the owner * All variable keys this is holding
*/ *
public DataUnit getOwner() { * @return Set of all variable names.
return owner; */
} public Set<String> getVarKeyList() {
public boolean isEmpty() { return variables.keySet();
return variables.isEmpty(); }
}
/**
* verify is a var exists
*
* @param name the key name of the var
* @return true if that var exists
*/
public boolean hasVar(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();
}
/**
* Remove a var from the list
*
* @param name
*/
public void removeVar(String name) {
try {
variables.remove(name);
} catch (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

@ -6,8 +6,6 @@ import java.util.Map;
import org.anjocaido.groupmanager.data.Group; import org.anjocaido.groupmanager.data.Group;
/** /**
* This container holds all Groups loaded from the relevant groupsFile. * This container holds all Groups loaded from the relevant groupsFile.
* *
@ -31,9 +29,11 @@ public class GroupsDataHolder {
* Constructor * Constructor
*/ */
protected GroupsDataHolder() { protected GroupsDataHolder() {
} }
public void setDataSource(WorldDataHolder dataSource) { public void setDataSource(WorldDataHolder dataSource) {
this.dataSource = dataSource; this.dataSource = dataSource;
//push this data source to the users, so they pull the correct groups data. //push this data source to the users, so they pull the correct groups data.
for (Group group : groups.values()) for (Group group : groups.values())
@ -44,6 +44,7 @@ public class GroupsDataHolder {
* @return the defaultGroup * @return the defaultGroup
*/ */
public Group getDefaultGroup() { public Group getDefaultGroup() {
return defaultGroup; return defaultGroup;
} }
@ -51,6 +52,7 @@ public class GroupsDataHolder {
* @param defaultGroup the defaultGroup to set * @param defaultGroup the defaultGroup to set
*/ */
public void setDefaultGroup(Group defaultGroup) { public void setDefaultGroup(Group defaultGroup) {
this.defaultGroup = defaultGroup; this.defaultGroup = defaultGroup;
} }
@ -58,20 +60,23 @@ public class GroupsDataHolder {
* @return the groups * @return the groups
*/ */
public Map<String, Group> getGroups() { public Map<String, Group> getGroups() {
return groups; return groups;
} }
/** /**
* @param groups the groups to set * @param groups the groups to set
*/ */
public void setGroups(Map<String, Group> groups) { public void setGroups(Map<String, Group> groups) {
this.groups = groups; this.groups = groups;
} }
/** /**
* @return the groupsFile * @return the groupsFile
*/ */
public File getGroupsFile() { public File getGroupsFile() {
return groupsFile; return groupsFile;
} }
@ -79,6 +84,7 @@ public class GroupsDataHolder {
* @param groupsFile the groupsFile to set * @param groupsFile the groupsFile to set
*/ */
public void setGroupsFile(File groupsFile) { public void setGroupsFile(File groupsFile) {
this.groupsFile = groupsFile; this.groupsFile = groupsFile;
} }
@ -86,6 +92,7 @@ public class GroupsDataHolder {
* @return the haveGroupsChanged * @return the haveGroupsChanged
*/ */
public boolean HaveGroupsChanged() { public boolean HaveGroupsChanged() {
return haveGroupsChanged; return haveGroupsChanged;
} }
@ -93,6 +100,7 @@ public class GroupsDataHolder {
* @param haveGroupsChanged the haveGroupsChanged to set * @param haveGroupsChanged the haveGroupsChanged to set
*/ */
public void setGroupsChanged(boolean haveGroupsChanged) { public void setGroupsChanged(boolean haveGroupsChanged) {
this.haveGroupsChanged = haveGroupsChanged; this.haveGroupsChanged = haveGroupsChanged;
} }
@ -100,6 +108,7 @@ public class GroupsDataHolder {
* @return the timeStampGroups * @return the timeStampGroups
*/ */
public long getTimeStampGroups() { public long getTimeStampGroups() {
return timeStampGroups; return timeStampGroups;
} }
@ -107,6 +116,7 @@ public class GroupsDataHolder {
* @param timeStampGroups the timeStampGroups to set * @param timeStampGroups the timeStampGroups to set
*/ */
public void setTimeStampGroups(long timeStampGroups) { public void setTimeStampGroups(long timeStampGroups) {
this.timeStampGroups = timeStampGroups; this.timeStampGroups = timeStampGroups;
} }

View file

@ -11,195 +11,204 @@ import java.util.Map;
import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.data.User;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class OverloadedWorldHolder extends WorldDataHolder { public class OverloadedWorldHolder extends WorldDataHolder {
/** /**
* *
*/ */
protected Map<String, User> overloadedUsers = new HashMap<String, User>(); protected Map<String, User> overloadedUsers = new HashMap<String, User>();
/** /**
* *
* @param ph * @param ph
*/ */
public OverloadedWorldHolder(WorldDataHolder ph) { public OverloadedWorldHolder(WorldDataHolder ph) {
super(ph.getName());
this.setGroupsFile(ph.getGroupsFile());
this.setUsersFile(ph.getUsersFile());
//this.setDefaultGroup(ph.getDefaultGroup());
this.groups = ph.groups;
this.users = ph.users;
}
/** super(ph.getName());
* this.setGroupsFile(ph.getGroupsFile());
* @param userName this.setUsersFile(ph.getUsersFile());
* @return user object or a new user if none exists. this.groups = ph.groups;
*/ this.users = ph.users;
@Override }
public User getUser(String userName) {
//OVERLOADED CODE
String userNameLowered = userName.toLowerCase();
if (overloadedUsers.containsKey(userNameLowered)) {
return overloadedUsers.get(userNameLowered);
}
//END CODE
if (getUsers().containsKey(userNameLowered)) {
return getUsers().get(userNameLowered);
}
User newUser = createUser(userName);
setUsersChanged(true);
return newUser;
}
/** /**
* *
* @param theUser * @param userName
*/ * @return user object or a new user if none exists.
@Override */
public void addUser(User theUser) { @Override
if (theUser.getDataSource() != this) { public User getUser(String userName) {
theUser = theUser.clone(this);
}
if (theUser == null) {
return;
}
if ((theUser.getGroup() == null) || (!getGroups().containsKey(theUser.getGroupName().toLowerCase()))) {
theUser.setGroup(getDefaultGroup());
}
//OVERLOADED CODE
if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) {
overloadedUsers.remove(theUser.getName().toLowerCase());
overloadedUsers.put(theUser.getName().toLowerCase(), theUser);
return;
}
//END CODE
removeUser(theUser.getName());
getUsers().put(theUser.getName().toLowerCase(), theUser);
setUsersChanged(true);
}
/** //OVERLOADED CODE
* String userNameLowered = userName.toLowerCase();
* @param userName if (overloadedUsers.containsKey(userNameLowered)) {
* @return true if removed/false if not found. return overloadedUsers.get(userNameLowered);
*/ }
@Override //END CODE
public boolean removeUser(String userName) { if (getUsers().containsKey(userNameLowered)) {
//OVERLOADED CODE return getUsers().get(userNameLowered);
if (overloadedUsers.containsKey(userName.toLowerCase())) { }
overloadedUsers.remove(userName.toLowerCase()); User newUser = createUser(userName);
return true; setUsersChanged(true);
} return newUser;
//END CODE }
if (getUsers().containsKey(userName.toLowerCase())) {
getUsers().remove(userName.toLowerCase());
setUsersChanged(true);
return true;
}
return false;
}
@Override /**
public boolean removeGroup(String groupName) { *
if (groupName.equals(getDefaultGroup())) { * @param theUser
return false; */
} @Override
for (String key : getGroups().keySet()) { public void addUser(User theUser) {
if (groupName.equalsIgnoreCase(key)) {
getGroups().remove(key);
for (String userKey : getUsers().keySet()) {
User user = getUsers().get(userKey);
if (user.getGroupName().equalsIgnoreCase(key)) {
user.setGroup(getDefaultGroup());
}
} if (theUser.getDataSource() != this) {
//OVERLOADED CODE theUser = theUser.clone(this);
for (String userKey : overloadedUsers.keySet()) { }
User user = overloadedUsers.get(userKey); if (theUser == null) {
if (user.getGroupName().equalsIgnoreCase(key)) { return;
user.setGroup(getDefaultGroup()); }
} if ((theUser.getGroup() == null) || (!getGroups().containsKey(theUser.getGroupName().toLowerCase()))) {
theUser.setGroup(getDefaultGroup());
}
//OVERLOADED CODE
if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) {
overloadedUsers.remove(theUser.getName().toLowerCase());
overloadedUsers.put(theUser.getName().toLowerCase(), theUser);
return;
}
//END CODE
removeUser(theUser.getName());
getUsers().put(theUser.getName().toLowerCase(), theUser);
setUsersChanged(true);
}
} /**
//END OVERLOAD *
setGroupsChanged(true); * @param userName
return true; * @return true if removed/false if not found.
} */
} @Override
return false; public boolean removeUser(String userName) {
}
/** //OVERLOADED CODE
* if (overloadedUsers.containsKey(userName.toLowerCase())) {
* @return Collection of all users overloadedUsers.remove(userName.toLowerCase());
*/ return true;
@Override }
public Collection<User> getUserList() { //END CODE
Collection<User> overloadedList = new ArrayList<User>(); if (getUsers().containsKey(userName.toLowerCase())) {
Collection<User> normalList = getUsers().values(); getUsers().remove(userName.toLowerCase());
for (User u : normalList) { setUsersChanged(true);
if (overloadedUsers.containsKey(u.getName().toLowerCase())) { return true;
overloadedList.add(overloadedUsers.get(u.getName().toLowerCase())); }
} else { return false;
overloadedList.add(u); }
}
}
return overloadedList;
}
/** @Override
* public boolean removeGroup(String groupName) {
* @param userName
* @return true if user is overloaded.
*/
public boolean isOverloaded(String userName) {
return overloadedUsers.containsKey(userName.toLowerCase());
}
/** if (groupName.equals(getDefaultGroup())) {
* return false;
* @param userName }
*/ for (String key : getGroups().keySet()) {
public void overloadUser(String userName) { if (groupName.equalsIgnoreCase(key)) {
if (!isOverloaded(userName)) { getGroups().remove(key);
User theUser = getUser(userName); for (String userKey : getUsers().keySet()) {
theUser = theUser.clone(); User user = getUsers().get(userKey);
if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) { if (user.getGroupName().equalsIgnoreCase(key)) {
overloadedUsers.remove(theUser.getName().toLowerCase()); user.setGroup(getDefaultGroup());
} }
overloadedUsers.put(theUser.getName().toLowerCase(), theUser);
}
}
/** }
* //OVERLOADED CODE
* @param userName for (String userKey : overloadedUsers.keySet()) {
*/ User user = overloadedUsers.get(userKey);
public void removeOverload(String userName) { if (user.getGroupName().equalsIgnoreCase(key)) {
overloadedUsers.remove(userName.toLowerCase()); user.setGroup(getDefaultGroup());
} }
/** }
* Gets the user in normal state. Surpassing the overload state. //END OVERLOAD
* It doesn't affect permissions. But it enables plugins change the setGroupsChanged(true);
* actual user permissions even in overload mode. return true;
* }
* @param userName }
* @return user object return false;
*/ }
public User surpassOverload(String userName) {
if (!isOverloaded(userName)) { /**
return getUser(userName); *
} * @return Collection of all users
if (getUsers().containsKey(userName.toLowerCase())) { */
return getUsers().get(userName.toLowerCase()); @Override
} public Collection<User> getUserList() {
User newUser = createUser(userName);
return newUser; Collection<User> overloadedList = new ArrayList<User>();
} Collection<User> normalList = getUsers().values();
for (User u : normalList) {
if (overloadedUsers.containsKey(u.getName().toLowerCase())) {
overloadedList.add(overloadedUsers.get(u.getName().toLowerCase()));
} else {
overloadedList.add(u);
}
}
return overloadedList;
}
/**
*
* @param userName
* @return true if user is overloaded.
*/
public boolean isOverloaded(String userName) {
return overloadedUsers.containsKey(userName.toLowerCase());
}
/**
*
* @param userName
*/
public void overloadUser(String userName) {
if (!isOverloaded(userName)) {
User theUser = getUser(userName);
theUser = theUser.clone();
if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) {
overloadedUsers.remove(theUser.getName().toLowerCase());
}
overloadedUsers.put(theUser.getName().toLowerCase(), theUser);
}
}
/**
*
* @param userName
*/
public void removeOverload(String userName) {
overloadedUsers.remove(userName.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 userName
* @return user object
*/
public User surpassOverload(String userName) {
if (!isOverloaded(userName)) {
return getUser(userName);
}
if (getUsers().containsKey(userName.toLowerCase())) {
return getUsers().get(userName.toLowerCase());
}
User newUser = createUser(userName);
return newUser;
}
} }

View file

@ -6,8 +6,6 @@ import java.util.Map;
import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.data.User;
/** /**
* This container holds all Users loaded from the relevant usersFile. * This container holds all Users loaded from the relevant usersFile.
* *
@ -30,27 +28,31 @@ public class UsersDataHolder {
* Constructor * Constructor
*/ */
protected UsersDataHolder() { protected UsersDataHolder() {
} }
public void setDataSource(WorldDataHolder dataSource) { public void setDataSource(WorldDataHolder dataSource) {
this.dataSource = dataSource; this.dataSource = dataSource;
//push this data source to the users, so they pull the correct groups data. //push this data source to the users, so they pull the correct groups data.
for (User user : users.values()) for (User user : users.values())
user.setDataSource(this.dataSource); user.setDataSource(this.dataSource);
} }
/** /**
* @return the users * @return the users
*/ */
public Map<String, User> getUsers() { public Map<String, User> getUsers() {
return users; return users;
} }
/** /**
* @param users the users to set * @param users the users to set
*/ */
public void setUsers(Map<String, User> users) { public void setUsers(Map<String, User> users) {
this.users = users; this.users = users;
} }
@ -58,6 +60,7 @@ public class UsersDataHolder {
* @return the usersFile * @return the usersFile
*/ */
public File getUsersFile() { public File getUsersFile() {
return usersFile; return usersFile;
} }
@ -65,6 +68,7 @@ public class UsersDataHolder {
* @param usersFile the usersFile to set * @param usersFile the usersFile to set
*/ */
public void setUsersFile(File usersFile) { public void setUsersFile(File usersFile) {
this.usersFile = usersFile; this.usersFile = usersFile;
} }
@ -72,6 +76,7 @@ public class UsersDataHolder {
* @return the haveUsersChanged * @return the haveUsersChanged
*/ */
public boolean HaveUsersChanged() { public boolean HaveUsersChanged() {
return haveUsersChanged; return haveUsersChanged;
} }
@ -79,6 +84,7 @@ public class UsersDataHolder {
* @param haveUsersChanged the haveUsersChanged to set * @param haveUsersChanged the haveUsersChanged to set
*/ */
public void setUsersChanged(boolean haveUsersChanged) { public void setUsersChanged(boolean haveUsersChanged) {
this.haveUsersChanged = haveUsersChanged; this.haveUsersChanged = haveUsersChanged;
} }
@ -86,6 +92,7 @@ public class UsersDataHolder {
* @return the timeStampUsers * @return the timeStampUsers
*/ */
public long getTimeStampUsers() { public long getTimeStampUsers() {
return timeStampUsers; return timeStampUsers;
} }
@ -93,6 +100,7 @@ public class UsersDataHolder {
* @param timeStampUsers the timeStampUsers to set * @param timeStampUsers the timeStampUsers to set
*/ */
public void setTimeStampUsers(long timeStampUsers) { public void setTimeStampUsers(long timeStampUsers) {
this.timeStampUsers = timeStampUsers; this.timeStampUsers = timeStampUsers;
} }

View file

@ -6,79 +6,82 @@ import org.bukkit.Bukkit;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
/** /**
* @author ElgarL * @author ElgarL
* *
*/ */
public class GMGroupEvent extends Event { public class GMGroupEvent extends Event {
/** /**
* *
*/ */
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
////////////////////////////// return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected Group group; protected Group group;
protected String groupName; protected String groupName;
protected Action action;
public GMGroupEvent(Group group, Action action) { protected Action action;
super();
this.group = group; public GMGroupEvent(Group group, Action action) {
this.action = action;
this.groupName = group.getName();
}
public GMGroupEvent(String groupName, Action action) {
super();
this.groupName = groupName; super();
this.action = action;
}
public Action getAction(){
return this.action;
}
public Group getGroup() { this.group = group;
return group; this.action = action;
} this.groupName = group.getName();
}
public String getGroupName() {
return groupName; public GMGroupEvent(String groupName, Action action) {
}
super();
public enum Action {
GROUP_PERMISSIONS_CHANGED, this.groupName = groupName;
GROUP_INHERITANCE_CHANGED, this.action = action;
GROUP_INFO_CHANGED, }
GROUP_ADDED,
GROUP_REMOVED, public Action getAction() {
}
return this.action;
public void schedule(final GMGroupEvent event) { }
public Group getGroup() {
return group;
}
public String getGroupName() {
return groupName;
}
public enum Action {
GROUP_PERMISSIONS_CHANGED, GROUP_INHERITANCE_CHANGED, GROUP_INFO_CHANGED, GROUP_ADDED, GROUP_REMOVED,
}
public void schedule(final GMGroupEvent event) {
if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("GroupManager"), new Runnable() { if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("GroupManager"), new Runnable() {
@Override @Override
public void run() { public void run() {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
} }
}, 1) == -1) }, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event."); GroupManager.logger.warning("Could not schedule GM Event.");
} }
} }

View file

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

View file

@ -6,81 +6,82 @@ import org.bukkit.Bukkit;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
/** /**
* @author ElgarL * @author ElgarL
* *
*/ */
public class GMUserEvent extends Event { public class GMUserEvent extends Event {
/** /**
* *
*/ */
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
////////////////////////////// return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
//////////////////////////////
protected User user; protected User user;
protected String userName; protected String userName;
protected Action action;
public GMUserEvent(User user, Action action) { protected Action action;
super();
this.user = user; public GMUserEvent(User user, Action action) {
this.action = action;
this.userName = user.getName();
}
public GMUserEvent(String userName, Action action) {
super();
this.userName = userName; super();
this.action = action;
}
public Action getAction(){
return this.action;
}
public User getUser() { this.user = user;
return user; this.action = action;
} this.userName = user.getName();
}
public String getUserName() {
return userName; public GMUserEvent(String userName, Action action) {
}
super();
public enum Action {
USER_PERMISSIONS_CHANGED, this.userName = userName;
USER_INHERITANCE_CHANGED, this.action = action;
USER_INFO_CHANGED, }
USER_GROUP_CHANGED,
USER_SUBGROUP_CHANGED, public Action getAction() {
USER_ADDED,
USER_REMOVED, return this.action;
} }
public void schedule(final GMUserEvent event) { public User getUser() {
return user;
}
public String getUserName() {
return userName;
}
public enum Action {
USER_PERMISSIONS_CHANGED, USER_INHERITANCE_CHANGED, USER_INFO_CHANGED, USER_GROUP_CHANGED, USER_SUBGROUP_CHANGED, USER_ADDED, USER_REMOVED,
}
public void schedule(final GMUserEvent event) {
if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("GroupManager"), new Runnable() { if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Bukkit.getPluginManager().getPlugin("GroupManager"), new Runnable() {
@Override @Override
public void run() { public void run() {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
} }
}, 1) == -1) }, 1) == -1)
GroupManager.logger.warning("Could not schedule GM Event."); GroupManager.logger.warning("Could not schedule GM Event.");
} }
} }

View file

@ -6,31 +6,33 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldInitEvent;
/** /**
* @author ElgarL * @author ElgarL
* *
* Handle new world creation from other plugins * Handle new world creation from other plugins
* *
*/ */
public class GMWorldListener implements Listener { public class GMWorldListener implements Listener {
private final GroupManager plugin; private final GroupManager plugin;
public GMWorldListener(GroupManager instance) { public GMWorldListener(GroupManager instance) {
plugin = instance; plugin = instance;
registerEvents(); registerEvents();
} }
private void registerEvents() { private void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
} plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
String worldName = event.getWorld().getName();
String worldName = event.getWorld().getName();
if (GroupManager.isLoaded() && !plugin.getWorldsHolder().isInList(worldName)) {
if (GroupManager.isLoaded() && !plugin.getWorldsHolder().isInList(worldName)) {
GroupManager.logger.info("New world detected..."); GroupManager.logger.info("New world detected...");
GroupManager.logger.info("Creating data for: " + worldName); GroupManager.logger.info("Creating data for: " + worldName);
plugin.getWorldsHolder().setupWorldFolder(worldName); plugin.getWorldsHolder().setupWorldFolder(worldName);

View file

@ -3,40 +3,51 @@ package org.anjocaido.groupmanager.events;
import org.anjocaido.groupmanager.data.Group; import org.anjocaido.groupmanager.data.Group;
import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.data.User;
/** /**
* @author ElgarL * @author ElgarL
* *
* Handles all Event generation. * Handles all Event generation.
* *
*/ */
public class GroupManagerEventHandler { public class GroupManagerEventHandler {
protected static void callEvent(GMGroupEvent event) { protected static void callEvent(GMGroupEvent event) {
event.schedule(event); event.schedule(event);
} }
protected static void callEvent(GMUserEvent event) { protected static void callEvent(GMUserEvent event) {
event.schedule(event); event.schedule(event);
} }
protected static void callEvent(GMSystemEvent event) { protected static void callEvent(GMSystemEvent event) {
event.schedule(event); event.schedule(event);
} }
public static void callEvent(Group group, GMGroupEvent.Action action) { public static void callEvent(Group group, GMGroupEvent.Action action) {
callEvent(new GMGroupEvent(group, action)); callEvent(new GMGroupEvent(group, action));
} }
public static void callEvent(String groupName, GMGroupEvent.Action action) { public static void callEvent(String groupName, GMGroupEvent.Action action) {
callEvent(new GMGroupEvent(groupName, action)); callEvent(new GMGroupEvent(groupName, action));
} }
public static void callEvent(User user, GMUserEvent.Action action) { public static void callEvent(User user, GMUserEvent.Action action) {
callEvent(new GMUserEvent(user, action)); callEvent(new GMUserEvent(user, action));
} }
public static void callEvent(String userName, GMUserEvent.Action action) { public static void callEvent(String userName, GMUserEvent.Action action) {
callEvent(new GMUserEvent(userName, action)); callEvent(new GMUserEvent(userName, action));
} }
public static void callEvent(GMSystemEvent.Action action) { public static void callEvent(GMSystemEvent.Action action) {
callEvent(new GMSystemEvent(action)); callEvent(new GMSystemEvent(action));
} }
} }

View file

@ -16,7 +16,6 @@ import org.anjocaido.groupmanager.data.Group;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder; import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.data.User; import org.anjocaido.groupmanager.data.User;
import org.anjocaido.groupmanager.utils.PermissionCheckResult; import org.anjocaido.groupmanager.utils.PermissionCheckResult;
import org.anjocaido.groupmanager.utils.PermissionCheckResult.Type;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
/** /**
@ -27,7 +26,7 @@ import org.bukkit.entity.Player;
* *
* It holds permissions only for one single world. * It holds permissions only for one single world.
* *
* @author gabrielcouto * @author gabrielcouto, ElgarL
*/ */
public class AnjoPermissionsHandler extends PermissionsReaderInterface { public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@ -39,6 +38,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @param holder * @param holder
*/ */
public AnjoPermissionsHandler(WorldDataHolder holder) { public AnjoPermissionsHandler(WorldDataHolder holder) {
ph = holder; ph = holder;
} }
@ -51,6 +51,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean has(Player player, String permission) { public boolean has(Player player, String permission) {
return permission(player, permission); return permission(player, permission);
} }
@ -63,6 +64,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean permission(Player player, String permission) { public boolean permission(Player player, String permission) {
return checkUserPermission(ph.getUser(player.getName()).updatePlayer(player), permission); return checkUserPermission(ph.getUser(player.getName()).updatePlayer(player), permission);
} }
@ -74,6 +76,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return true if the player has the permission * @return true if the player has the permission
*/ */
public boolean permission(String playerName, String permission) { public boolean permission(String playerName, String permission) {
return checkUserPermission(ph.getUser(playerName), permission); return checkUserPermission(ph.getUser(playerName), permission);
} }
@ -85,6 +88,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroup(String userName) { public String getGroup(String userName) {
return ph.getUser(userName).getGroup().getName(); return ph.getUser(userName).getGroup().getName();
} }
@ -97,10 +101,11 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public List<String> getAllPlayersPermissions(String userName) { public List<String> getAllPlayersPermissions(String userName) {
List<String> perms = new ArrayList<String>(); List<String> perms = new ArrayList<String>();
perms.addAll(getAllPlayersPermissions(userName, true)); perms.addAll(getAllPlayersPermissions(userName, true));
return perms; return perms;
} }
@ -118,33 +123,32 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
// Add the players own permissions. // Add the players own permissions.
playerPermArray.addAll(populatePerms(ph.getUser(userName).getPermissionList(), includeChildren)); playerPermArray.addAll(populatePerms(ph.getUser(userName).getPermissionList(), includeChildren));
ArrayList<String> alreadyProcessed = new ArrayList<String>(); ArrayList<String> alreadyProcessed = new ArrayList<String>();
// fetch all group permissions // fetch all group permissions
for (String group : getGroups(userName)) { for (String group : getGroups(userName)) {
// Don't process a group more than once. // Don't process a group more than once.
if (!alreadyProcessed.contains(group)) { if (!alreadyProcessed.contains(group)) {
alreadyProcessed.add(group); alreadyProcessed.add(group);
Set<String> groupPermArray = new HashSet<String>(); Set<String> groupPermArray = new HashSet<String>();
if (group.startsWith("g:") && GroupManager.getGlobalGroups().hasGroup(group)) { if (group.startsWith("g:") && GroupManager.getGlobalGroups().hasGroup(group)) {
// GlobalGroups // GlobalGroups
groupPermArray = populatePerms(GroupManager.getGlobalGroups().getGroupsPermissions(group), includeChildren); groupPermArray = populatePerms(GroupManager.getGlobalGroups().getGroupsPermissions(group), includeChildren);
} else { } else {
// World Groups // World Groups
groupPermArray = populatePerms(ph.getGroup(group).getPermissionList(), includeChildren); groupPermArray = populatePerms(ph.getGroup(group).getPermissionList(), includeChildren);
} }
// Add all group permissions, unless negated by earlier permissions. // Add all group permissions, unless negated by earlier permissions.
for (String perm : groupPermArray) { for (String perm : groupPermArray) {
boolean negated = (perm.startsWith("-")); boolean negated = (perm.startsWith("-"));
// Perm doesn't already exists and there is no negation for it // Perm doesn't already exists and there is no negation for it
// or It's a negated perm where a normal perm doesn't exists (don't allow inheritance to negate higher perms) // or It's a negated perm where a normal perm doesn't exists (don't allow inheritance to negate higher perms)
if ((!negated && !playerPermArray.contains(perm) && !playerPermArray.contains("-" + perm)) if ((!negated && !playerPermArray.contains(perm) && !playerPermArray.contains("-" + perm)) || (negated && !playerPermArray.contains(perm.substring(1)) && !playerPermArray.contains("-" + perm)))
|| (negated && !playerPermArray.contains(perm.substring(1)) && !playerPermArray.contains("-" + perm)))
playerPermArray.add(perm); playerPermArray.add(perm);
} }
} }
@ -154,68 +158,69 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return playerPermArray; return playerPermArray;
} }
private Set<String> populatePerms (List<String> permsList, boolean includeChildren) { private Set<String> populatePerms(List<String> permsList, boolean includeChildren) {
// Create a new array so it's modifiable. // Create a new array so it's modifiable.
List<String> perms = new ArrayList<String>(permsList); List<String> perms = new ArrayList<String>(permsList);
Set<String> permArray = new HashSet<String>(); Set<String> permArray = new HashSet<String>();
Boolean allPerms = false; Boolean allPerms = false;
// Allow * node to populate ALL permissions to Bukkit. // Allow * node to populate ALL permissions to Bukkit.
if (perms.contains("*")) { if (perms.contains("*")) {
permArray.addAll(GroupManager.BukkitPermissions.getAllRegisteredPermissions(includeChildren)); permArray.addAll(GroupManager.BukkitPermissions.getAllRegisteredPermissions(includeChildren));
allPerms = true; allPerms = true;
perms.remove("*"); perms.remove("*");
} }
for (String perm : perms) { for (String perm : perms) {
/**
* all permission sets are passed here pre-sorted, alphabetically.
* This means negated nodes will be processed before all permissions
* other than *.
*/
boolean negated = perm.startsWith("-");
if (!permArray.contains(perm)) {
permArray.add(perm);
if ((negated) && (permArray.contains(perm.substring(1))))
permArray.remove(perm.substring(1));
/** /**
* all permission sets are passed here pre-sorted, alphabetically. * Process child nodes if required,
* This means negated nodes will be processed before all permissions * or this is a negated node AND we used * to include all
* other than *. * permissions,
* in which case we need to remove all children of that node.
*/ */
boolean negated = perm.startsWith("-"); if ((includeChildren) || (negated && allPerms)) {
if (!permArray.contains(perm)) { Map<String, Boolean> children = GroupManager.BukkitPermissions.getAllChildren((negated ? perm.substring(1) : perm), new HashSet<String>());
permArray.add(perm);
if (children != null) {
if ((negated) && (permArray.contains(perm.substring(1)))) if (negated)
permArray.remove(perm.substring(1)); if (allPerms) {
/** // Remove children of negated nodes
* Process child nodes if required, for (String child : children.keySet())
* or this is a negated node AND we used * to include all permissions, if (children.get(child))
* in which case we need to remove all children of that node. if (permArray.contains(child))
*/ permArray.remove(child);
if ((includeChildren) || (negated && allPerms)) {
Map<String, Boolean> children = GroupManager.BukkitPermissions.getAllChildren((negated ? perm.substring(1) : perm), new HashSet<String>());
if (children != null) {
if (negated)
if (allPerms) {
// Remove children of negated nodes
for (String child : children.keySet())
if (children.get(child))
if (permArray.contains(child))
permArray.remove(child);
} else { } else {
// Add child nodes // Add child nodes
for (String child : children.keySet()) for (String child : children.keySet())
if (children.get(child)) if (children.get(child))
if ((!permArray.contains(child)) && (!permArray.contains("-" + child))) if ((!permArray.contains(child)) && (!permArray.contains("-" + child)))
permArray.add(child); permArray.add(child);
} }
}
} }
} }
}
} }
return permArray; return permArray;
} }
@ -236,6 +241,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean inGroup(String name, String group) { public boolean inGroup(String name, String group) {
if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) { if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) {
return true; return true;
} }
@ -326,6 +332,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupPrefix(String groupName) { public String getGroupPrefix(String groupName) {
Group g = ph.getGroup(groupName); Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return ""; return "";
@ -341,6 +348,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupSuffix(String groupName) { public String getGroupSuffix(String groupName) {
Group g = ph.getGroup(groupName); Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return ""; return "";
@ -357,6 +365,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean canGroupBuild(String groupName) { public boolean canGroupBuild(String groupName) {
Group g = ph.getGroup(groupName); Group g = ph.getGroup(groupName);
if (g == null) { if (g == null) {
return false; return false;
@ -374,6 +383,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getGroupPermissionString(String groupName, String variable) { public String getGroupPermissionString(String groupName, String variable) {
Group start = ph.getGroup(groupName); Group start = ph.getGroup(groupName);
if (start == null) { if (start == null) {
return null; return null;
@ -395,6 +405,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getGroupPermissionInteger(String groupName, String variable) { public int getGroupPermissionInteger(String groupName, String variable) {
Group start = ph.getGroup(groupName); Group start = ph.getGroup(groupName);
if (start == null) { if (start == null) {
return -1; return -1;
@ -416,6 +427,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getGroupPermissionBoolean(String group, String variable) { public boolean getGroupPermissionBoolean(String group, String variable) {
Group start = ph.getGroup(group); Group start = ph.getGroup(group);
if (start == null) { if (start == null) {
return false; return false;
@ -437,6 +449,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getGroupPermissionDouble(String group, String variable) { public double getGroupPermissionDouble(String group, String variable) {
Group start = ph.getGroup(group); Group start = ph.getGroup(group);
if (start == null) { if (start == null) {
return -1; return -1;
@ -457,6 +470,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getUserPermissionString(String user, String variable) { public String getUserPermissionString(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return ""; return "";
@ -473,6 +487,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getUserPermissionInteger(String user, String variable) { public int getUserPermissionInteger(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -489,6 +504,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getUserPermissionBoolean(String user, String variable) { public boolean getUserPermissionBoolean(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return false; return false;
@ -505,6 +521,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getUserPermissionDouble(String user, String variable) { public double getUserPermissionDouble(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -523,6 +540,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String getPermissionString(String user, String variable) { public String getPermissionString(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return ""; return "";
@ -562,6 +580,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public int getPermissionInteger(String user, String variable) { public int getPermissionInteger(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1; return -1;
@ -601,6 +620,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public boolean getPermissionBoolean(String user, String variable) { public boolean getPermissionBoolean(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return false; return false;
@ -640,6 +660,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public double getPermissionDouble(String user, String variable) { public double getPermissionDouble(String user, String variable) {
User auser = ph.getUser(user); User auser = ph.getUser(user);
if (auser == null) { if (auser == null) {
return -1.0D; return -1.0D;
@ -676,6 +697,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkUserOnlyPermission(User user, String permission) { public PermissionCheckResult checkUserOnlyPermission(User user, String permission) {
user.sortPermissions(); user.sortPermissions();
PermissionCheckResult result = new PermissionCheckResult(); PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = permission; result.askedPermission = permission;
@ -699,6 +721,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return the node if permission is found. if not found, return null * @return the node if permission is found. if not found, return null
*/ */
public PermissionCheckResult checkGroupOnlyPermission(Group group, String permission) { public PermissionCheckResult checkGroupOnlyPermission(Group group, String permission) {
group.sortPermissions(); group.sortPermissions();
PermissionCheckResult result = new PermissionCheckResult(); PermissionCheckResult result = new PermissionCheckResult();
result.owner = group; result.owner = group;
@ -721,6 +744,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return true if permission was found. false if not, or was negated. * @return true if permission was found. false if not, or was negated.
*/ */
public boolean checkUserPermission(User user, String permission) { public boolean checkUserPermission(User user, String permission) {
PermissionCheckResult result = checkFullGMPermission(user, permission, true); PermissionCheckResult result = checkFullGMPermission(user, permission, true);
if (result.resultType == PermissionCheckResult.Type.EXCEPTION || result.resultType == PermissionCheckResult.Type.FOUND) { if (result.resultType == PermissionCheckResult.Type.EXCEPTION || result.resultType == PermissionCheckResult.Type.FOUND) {
return true; return true;
@ -752,6 +776,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkFullGMPermission(User user, String targetPermission, Boolean checkBukkit) { public PermissionCheckResult checkFullGMPermission(User user, String targetPermission, Boolean checkBukkit) {
PermissionCheckResult result = new PermissionCheckResult(); PermissionCheckResult result = new PermissionCheckResult();
result.accessLevel = targetPermission; result.accessLevel = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND; result.resultType = PermissionCheckResult.Type.NOTFOUND;
@ -798,37 +823,18 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return result; return result;
} }
/**
* Verifies if a given group has a variable. Including it's inheritance.
*
* it redirects to the other method now. This one was deprecated, and will
* be gone in a future release.
*
* @param start
* @param variable
* @param alreadyChecked
* @return returns the closest inherited group with the variable.
* @deprecated use now nextGroupWithVariable(Group start, String
* targetVariable)
*/
@Deprecated
public Group nextGroupWithVariable(Group start, String variable, List<Group> alreadyChecked) {
return nextGroupWithVariable(start, variable);
}
/** /**
* Returns the next group, including inheritance, which contains that * Returns the next group, including inheritance, which contains that
* variable name. * variable name.
* *
* It does Breadth-first search * It does Breadth-first search
* *
* @param start * @param start the starting group to look for
* the starting group to look for * @param targetVariable the variable name
* @param targetVariable
* the variable name
* @return The group if found. Null if not. * @return The group if found. Null if not.
*/ */
public Group nextGroupWithVariable(Group start, String targetVariable) { public Group nextGroupWithVariable(Group start, String targetVariable) {
if (start == null || targetVariable == null) { if (start == null || targetVariable == null) {
return null; return null;
} }
@ -852,39 +858,18 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return null; return null;
} }
/**
* Check if given group inherits another group.
*
* redirected to the other method. this is deprecated now. and will be gone
* in the future releases.
*
* @param start
* The group to start the search.
* @param askedGroup
* Name of the group you're looking for
* @param alreadyChecked
* groups to ignore(pass null on it, please)
* @return true if it inherits the group.
* @deprecated prefer using hasGroupInInheritance(Group start, String
* askedGroup)
*/
@Deprecated
public boolean searchGroupInInheritance(Group start, String askedGroup, List<Group> alreadyChecked) {
return hasGroupInInheritance(start, askedGroup);
}
/** /**
* Check if given group inherits another group. * Check if given group inherits another group.
* *
* It does Breadth-first search * It does Breadth-first search
* *
* @param start * @param start The group to start the search.
* The group to start the search. * @param askedGroup Name of the group you're looking for
* @param askedGroup
* Name of the group you're looking for
* @return true if it inherits the group. * @return true if it inherits the group.
*/ */
public boolean hasGroupInInheritance(Group start, String askedGroup) { public boolean hasGroupInInheritance(Group start, String askedGroup) {
if (start == null || askedGroup == null) { if (start == null || askedGroup == null) {
return false; return false;
} }
@ -908,25 +893,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return false; return false;
} }
/**
* Check if the group has given permission. Including it's inheritance
*
* @param start
* @param permission
* @param alreadyChecked
* @return true if PermissionCheckResult is EXCEPTION or FOUND
* @deprecated use the other checkGroupPermissionWithInheritance for
* everything
*/
@Deprecated
public boolean checkGroupPermissionWithInheritance(Group start, String permission, List<Group> alreadyChecked) {
PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission);
if (result.resultType.equals(Type.EXCEPTION) || result.resultType.equals(Type.FOUND)) {
return true;
}
return false;
}
/** /**
* Returns the result of permission check. Including inheritance. If found * Returns the result of permission check. Including inheritance. If found
* anything, the PermissionCheckResult that retuns will include the Group * anything, the PermissionCheckResult that retuns will include the Group
@ -942,6 +908,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult * @return PermissionCheckResult
*/ */
public PermissionCheckResult checkGroupPermissionWithInheritance(Group start, String targetPermission) { public PermissionCheckResult checkGroupPermissionWithInheritance(Group start, String targetPermission) {
if (start == null || targetPermission == null) { if (start == null || targetPermission == null) {
return null; return null;
} }
@ -970,42 +937,6 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
return result; return result;
} }
/**
* It uses checkGroupPermissionWithInheritance and cast the owner to Group
* type if result type was EXCEPTION or FOUND.
*
* @param start
* @param permission
* @param alreadyChecked
* @return the group that passed on test. null if no group passed.
* @deprecated use checkGroupPermissionWithInheritance for everything now.
*/
@Deprecated
public Group nextGroupWithPermission(Group start, String permission, List<Group> alreadyChecked) {
PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission);
if (result.resultType.equals(Type.EXCEPTION) || result.resultType.equals(Type.FOUND)) {
return (Group) checkGroupPermissionWithInheritance(start, permission).owner;
}
return null;
}
/**
* Return whole list of names of groups in a inheritance chain. Including a
* starting group.
*
* it now redirects to the other method. but get away from this one, it will
* disappear in a future release.
*
* @param start
* @param alreadyChecked
* @return the group that passed on test. null if no group passed.
* @deprecated use the other method with same name, instead
*/
@Deprecated
public ArrayList<String> listAllGroupsInherited(Group start, ArrayList<String> alreadyChecked) {
return listAllGroupsInherited(start);
}
/** /**
* Return whole list of names of groups in a inheritance chain. Including a * Return whole list of names of groups in a inheritance chain. Including a
* starting group. * starting group.
@ -1016,6 +947,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return the group that passed on test. null if no group passed. * @return the group that passed on test. null if no group passed.
*/ */
public ArrayList<String> listAllGroupsInherited(Group start) { public ArrayList<String> listAllGroupsInherited(Group start) {
if (start == null) { if (start == null) {
return null; return null;
} }
@ -1055,6 +987,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
* @return PermissionCheckResult.Type * @return PermissionCheckResult.Type
*/ */
public PermissionCheckResult.Type comparePermissionString(String userAccessLevel, String fullPermissionName) { public PermissionCheckResult.Type comparePermissionString(String userAccessLevel, String fullPermissionName) {
int userAccessLevelLength; int userAccessLevelLength;
if (userAccessLevel == null || fullPermissionName == null || fullPermissionName.length() == 0 || (userAccessLevelLength = userAccessLevel.length()) == 0) { if (userAccessLevel == null || fullPermissionName == null || fullPermissionName.length() == 0 || (userAccessLevelLength = userAccessLevel.length()) == 0) {
return PermissionCheckResult.Type.NOTFOUND; return PermissionCheckResult.Type.NOTFOUND;
@ -1080,12 +1013,9 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
} }
if (userAccessLevel.charAt(userAccessLevel.length() - 1) == '*') { if (userAccessLevel.charAt(userAccessLevel.length() - 1) == '*') {
return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, userAccessLevelLength - userAccessLevelOffset - 1) ? return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, userAccessLevelLength - userAccessLevelOffset - 1) ? result : PermissionCheckResult.Type.NOTFOUND;
result : PermissionCheckResult.Type.NOTFOUND;
} else { } else {
return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, return userAccessLevel.regionMatches(true, userAccessLevelOffset, fullPermissionName, fullPermissionNameOffset, Math.max(userAccessLevelLength - userAccessLevelOffset, fullPermissionName.length() - fullPermissionNameOffset)) ? result : PermissionCheckResult.Type.NOTFOUND;
Math.max(userAccessLevelLength - userAccessLevelOffset, fullPermissionName.length() - fullPermissionNameOffset)) ?
result : PermissionCheckResult.Type.NOTFOUND;
} }
} }
@ -1099,6 +1029,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@Override @Override
public String[] getGroups(String userName) { public String[] getGroups(String userName) {
ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup()); ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup());
for (Group subg : ph.getUser(userName).subGroupListCopy()) { for (Group subg : ph.getUser(userName).subGroupListCopy()) {
allGroups.addAll(listAllGroupsInherited(subg)); allGroups.addAll(listAllGroupsInherited(subg));
@ -1120,6 +1051,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
private Group breadthFirstSearch(Group start, String targerPermission) { private Group breadthFirstSearch(Group start, String targerPermission) {
if (start == null || targerPermission == null) { if (start == null || targerPermission == null) {
return null; return null;
} }
@ -1149,11 +1081,13 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public Group getDefaultGroup() { public Group getDefaultGroup() {
return ph.getDefaultGroup(); return ph.getDefaultGroup();
} }
@Override @Override
public String getInfoString(String entryName, String path, boolean isGroup) { public String getInfoString(String entryName, String path, boolean isGroup) {
if (isGroup) { if (isGroup) {
Group data = ph.getGroup(entryName); Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -1171,6 +1105,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public int getInfoInteger(String entryName, String path, boolean isGroup) { public int getInfoInteger(String entryName, String path, boolean isGroup) {
if (isGroup) { if (isGroup) {
Group data = ph.getGroup(entryName); Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -1188,6 +1123,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public double getInfoDouble(String entryName, String path, boolean isGroup) { public double getInfoDouble(String entryName, String path, boolean isGroup) {
if (isGroup) { if (isGroup) {
Group data = ph.getGroup(entryName); Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -1206,6 +1142,7 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public boolean getInfoBoolean(String entryName, String path, boolean isGroup) { public boolean getInfoBoolean(String entryName, String path, boolean isGroup) {
if (isGroup) { if (isGroup) {
Group data = ph.getGroup(entryName); Group data = ph.getGroup(entryName);
if (data == null) { if (data == null) {
@ -1223,21 +1160,25 @@ public class AnjoPermissionsHandler extends PermissionsReaderInterface {
@Override @Override
public void addUserInfo(String name, String path, Object data) { public void addUserInfo(String name, String path, Object data) {
ph.getUser(name).getVariables().addVar(path, data); ph.getUser(name).getVariables().addVar(path, data);
} }
@Override @Override
public void removeUserInfo(String name, String path) { public void removeUserInfo(String name, String path) {
ph.getUser(name).getVariables().removeVar(path); ph.getUser(name).getVariables().removeVar(path);
} }
@Override @Override
public void addGroupInfo(String name, String path, Object data) { public void addGroupInfo(String name, String path, Object data) {
ph.getGroup(name).getVariables().addVar(path, data); ph.getGroup(name).getVariables().addVar(path, data);
} }
@Override @Override
public void removeGroupInfo(String name, String path) { public void removeGroupInfo(String name, String path) {
ph.getGroup(name).getVariables().removeVar(path); ph.getGroup(name).getVariables().removeVar(path);
} }
} }

View file

@ -1,18 +1,19 @@
/* /*
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
*/ * USA.
*/
package org.anjocaido.groupmanager.permissions; package org.anjocaido.groupmanager.permissions;
@ -47,7 +48,6 @@ import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
/** /**
* *
* BukkitPermissions overrides to force GM reponses to Superperms * BukkitPermissions overrides to force GM reponses to Superperms
@ -62,11 +62,12 @@ public class BukkitPermissions {
protected boolean dumpAllPermissions = true; protected boolean dumpAllPermissions = true;
protected boolean dumpMatchedPermissions = true; protected boolean dumpMatchedPermissions = true;
private boolean player_join = false; private boolean player_join = false;
/** /**
* @return the player_join * @return the player_join
*/ */
public boolean isPlayer_join() { public boolean isPlayer_join() {
return player_join; return player_join;
} }
@ -74,6 +75,7 @@ public class BukkitPermissions {
* @param player_join the player_join to set * @param player_join the player_join to set
*/ */
public void setPlayer_join(boolean player_join) { public void setPlayer_join(boolean player_join) {
this.player_join = player_join; this.player_join = player_join;
} }
@ -92,6 +94,7 @@ public class BukkitPermissions {
} }
public BukkitPermissions(GroupManager plugin) { public BukkitPermissions(GroupManager plugin) {
this.plugin = plugin; this.plugin = plugin;
this.collectPermissions(); this.collectPermissions();
this.registerEvents(); this.registerEvents();
@ -101,35 +104,38 @@ public class BukkitPermissions {
} }
private void registerEvents() { private void registerEvents() {
PluginManager manager = plugin.getServer().getPluginManager(); PluginManager manager = plugin.getServer().getPluginManager();
manager.registerEvents(new PlayerEvents(), plugin); manager.registerEvents(new PlayerEvents(), plugin);
manager.registerEvents(new BukkitEvents(), plugin); manager.registerEvents(new BukkitEvents(), plugin);
} }
public void collectPermissions() { public void collectPermissions() {
registeredPermissions.clear(); registeredPermissions.clear();
for (Permission perm : Bukkit.getPluginManager().getPermissions()) { for (Permission perm : Bukkit.getPluginManager().getPermissions()) {
registeredPermissions.put(perm.getName().toLowerCase(), perm); registeredPermissions.put(perm.getName().toLowerCase(), perm);
} }
} }
public void updatePermissions(Player player) { public void updatePermissions(Player player) {
this.updatePermissions(player, null); this.updatePermissions(player, null);
} }
/** /**
* Push all permissions which are registered with GM for this player, on this world to Bukkit * Push all permissions which are registered with GM for this player, on
* this world to Bukkit
* and make it update for the child nodes. * and make it update for the child nodes.
* *
* @param player * @param player
* @param world * @param world
*/ */
public void updatePermissions(Player player, String world) { public void updatePermissions(Player player, String world) {
if (player == null || !GroupManager.isLoaded()) { if (player == null || !GroupManager.isLoaded()) {
return; return;
} }
@ -155,17 +161,18 @@ public class BukkitPermissions {
// Sort the perm list by parent/child, so it will push to superperms correctly. // Sort the perm list by parent/child, so it will push to superperms correctly.
playerPermArray = sort(playerPermArray); playerPermArray = sort(playerPermArray);
Boolean value = false; Boolean value = false;
for (String permission : playerPermArray) { for (String permission : playerPermArray) {
value = (!permission.startsWith("-")); value = (!permission.startsWith("-"));
newPerms.put((value? permission : permission.substring(1)), value); newPerms.put((value ? permission : permission.substring(1)), value);
} }
/** /**
* This is put in place until such a time as Bukkit pull 466 is implemented * This is put in place until such a time as Bukkit pull 466 is
* https://github.com/Bukkit/Bukkit/pull/466 * implemented
*/ * https://github.com/Bukkit/Bukkit/pull/466
*/
try { // Codename_B source try { // Codename_B source
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Boolean> orig = (Map<String, Boolean>) permissions.get(attachment); Map<String, Boolean> orig = (Map<String, Boolean>) permissions.get(attachment);
@ -182,7 +189,7 @@ public class BukkitPermissions {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Sort a permission node list by parent/child * Sort a permission node list by parent/child
* *
@ -190,20 +197,20 @@ public class BukkitPermissions {
* @return List sorted for priority * @return List sorted for priority
*/ */
private List<String> sort(List<String> permList) { private List<String> sort(List<String> permList) {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
for (String key : permList) { for (String key : permList) {
String a = key.charAt(0) == '-'? key.substring(1):key; String a = key.charAt(0) == '-' ? key.substring(1) : key;
Map<String, Boolean> allchildren = GroupManager.BukkitPermissions.getAllChildren(a, new HashSet<String>()); Map<String, Boolean> allchildren = GroupManager.BukkitPermissions.getAllChildren(a, new HashSet<String>());
if (allchildren != null) { if (allchildren != null) {
ListIterator<String> itr = result.listIterator(); ListIterator<String> itr = result.listIterator();
while (itr.hasNext()){ while (itr.hasNext()) {
String node = (String) itr.next(); String node = (String) itr.next();
String b = node.charAt(0) == '-'? node.substring(1):node; String b = node.charAt(0) == '-' ? node.substring(1) : node;
// Insert the parent node before the child // Insert the parent node before the child
if (allchildren.containsKey(b)) { if (allchildren.containsKey(b)) {
itr.set(key); itr.set(key);
@ -215,11 +222,10 @@ public class BukkitPermissions {
if (!result.contains(key)) if (!result.contains(key))
result.add(key); result.add(key);
} }
return result; return result;
} }
/** /**
* Fetch all permissions which are registered with superperms. * Fetch all permissions which are registered with superperms.
* {can include child nodes) * {can include child nodes)
@ -228,13 +234,13 @@ public class BukkitPermissions {
* @return List of all permission nodes * @return List of all permission nodes
*/ */
public List<String> getAllRegisteredPermissions(boolean includeChildren) { public List<String> getAllRegisteredPermissions(boolean includeChildren) {
List<String> perms = new ArrayList<String>(); List<String> perms = new ArrayList<String>();
for (String key : registeredPermissions.keySet()) { for (String key : registeredPermissions.keySet()) {
if (!perms.contains(key)) { if (!perms.contains(key)) {
perms.add(key); perms.add(key);
if (includeChildren) { if (includeChildren) {
Map<String, Boolean> children = getAllChildren(key, new HashSet<String>()); Map<String, Boolean> children = getAllChildren(key, new HashSet<String>());
if (children != null) { if (children != null) {
@ -244,32 +250,33 @@ public class BukkitPermissions {
} }
} }
} }
} }
return perms; return perms;
} }
/** /**
* Returns a map of ALL child permissions registered with bukkit * Returns a map of ALL child permissions registered with bukkit
* null is empty * null is empty
* *
* @param node * @param node
* @param playerPermArray current list of perms to check against for negations * @param playerPermArray current list of perms to check against for
* negations
* @return Map of child permissions * @return Map of child permissions
*/ */
public Map<String, Boolean> getAllChildren(String node, Set<String> playerPermArray) { public Map<String, Boolean> getAllChildren(String node, Set<String> playerPermArray) {
LinkedList<String> stack = new LinkedList<String>(); LinkedList<String> stack = new LinkedList<String>();
Map<String, Boolean> alreadyVisited = new HashMap<String, Boolean>(); Map<String, Boolean> alreadyVisited = new HashMap<String, Boolean>();
stack.push(node); stack.push(node);
alreadyVisited.put(node, true); alreadyVisited.put(node, true);
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
String now = stack.pop(); String now = stack.pop();
Map<String, Boolean> children = getChildren(now); Map<String, Boolean> children = getChildren(now);
if ((children != null) && (!playerPermArray.contains("-"+now))) { if ((children != null) && (!playerPermArray.contains("-" + now))) {
for (String childName : children.keySet()) { for (String childName : children.keySet()) {
if (!alreadyVisited.containsKey(childName)) { if (!alreadyVisited.containsKey(childName)) {
stack.push(childName); stack.push(childName);
@ -279,24 +286,26 @@ public class BukkitPermissions {
} }
} }
alreadyVisited.remove(node); alreadyVisited.remove(node);
if (!alreadyVisited.isEmpty()) return alreadyVisited; if (!alreadyVisited.isEmpty())
return alreadyVisited;
return null; return null;
} }
/** /**
* Returns a map of the child permissions (1 node deep) as registered with Bukkit. * Returns a map of the child permissions (1 node deep) as registered with
* Bukkit.
* null is empty * null is empty
* *
* @param node * @param node
* @return Map of child permissions * @return Map of child permissions
*/ */
public Map<String, Boolean> getChildren(String node) { public Map<String, Boolean> getChildren(String node) {
Permission perm = registeredPermissions.get(node.toLowerCase()); Permission perm = registeredPermissions.get(node.toLowerCase());
if (perm == null) if (perm == null)
return null; return null;
return perm.getChildren(); return perm.getChildren();
} }
@ -308,6 +317,7 @@ public class BukkitPermissions {
* @return List<String> of permissions * @return List<String> of permissions
*/ */
public List<String> listPerms(Player player) { public List<String> listPerms(Player player) {
List<String> perms = new ArrayList<String>(); List<String> perms = new ArrayList<String>();
/* /*
@ -332,25 +342,28 @@ public class BukkitPermissions {
* force Bukkit to update every OnlinePlayers permissions. * force Bukkit to update every OnlinePlayers permissions.
*/ */
public void updateAllPlayers() { public void updateAllPlayers() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) { for (Player player : Bukkit.getServer().getOnlinePlayers()) {
updatePermissions(player); updatePermissions(player);
} }
} }
/** /**
* force Bukkit to update this Players permissions. * force Bukkit to update this Players permissions.
*/ */
public void updatePlayer(Player player) { public void updatePlayer(Player player) {
if (player != null) if (player != null)
this.updatePermissions(player, null); this.updatePermissions(player, null);
} }
/** /**
* Force remove any attachments * Force remove any attachments
* *
* @param player * @param player
*/ */
private void removeAttachment(Player player) { private void removeAttachment(Player player) {
if (attachments.containsKey(player)) { if (attachments.containsKey(player)) {
try { try {
player.removeAttachment(attachments.get(player)); player.removeAttachment(attachments.get(player));
@ -363,15 +376,15 @@ public class BukkitPermissions {
attachments.remove(player); attachments.remove(player);
} }
} }
/** /**
* Remove all attachments in case of a restart or reload. * Remove all attachments in case of a restart or reload.
*/ */
public void removeAllAttachments() { public void removeAllAttachments() {
Iterator<Player> itr = attachments.keySet().iterator(); Iterator<Player> itr = attachments.keySet().iterator();
while (itr.hasNext()){ while (itr.hasNext()) {
Player player = itr.next(); Player player = itr.next();
try { try {
player.removeAttachment(attachments.get(player)); player.removeAttachment(attachments.get(player));
@ -389,20 +402,21 @@ public class BukkitPermissions {
* Player events tracked to cause Superperms updates * Player events tracked to cause Superperms updates
* *
* @author ElgarL * @author ElgarL
* *
*/ */
protected class PlayerEvents implements Listener { protected class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
setPlayer_join(true); setPlayer_join(true);
Player player = event.getPlayer(); Player player = event.getPlayer();
/* /*
* Tidy up any lose ends * Tidy up any lose ends
*/ */
removeAttachment(player); removeAttachment(player);
// force GM to create the player if they are not already listed. // force GM to create the player if they are not already listed.
if (plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(player.getName()) != null) { if (plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getUser(player.getName()) != null) {
setPlayer_join(false); setPlayer_join(false);
@ -410,29 +424,32 @@ public class BukkitPermissions {
} }
setPlayer_join(false); setPlayer_join(false);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { // has changed worlds public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { // has changed worlds
updatePermissions(event.getPlayer(), event.getPlayer().getWorld().getName()); updatePermissions(event.getPlayer(), event.getPlayer().getWorld().getName());
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerKick(PlayerKickEvent event) { public void onPlayerKick(PlayerKickEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
/* /*
* force remove any attachments as bukkit may not * force remove any attachments as bukkit may not
*/ */
removeAttachment(player); removeAttachment(player);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
if (!GroupManager.isLoaded()) if (!GroupManager.isLoaded())
return; return;
Player player = event.getPlayer(); Player player = event.getPlayer();
/* /*
* force remove any attachments as bukkit may not * force remove any attachments as bukkit may not
*/ */
@ -444,6 +461,7 @@ public class BukkitPermissions {
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPluginEnable(PluginEnableEvent event) { public void onPluginEnable(PluginEnableEvent event) {
if (!GroupManager.isLoaded()) if (!GroupManager.isLoaded())
return; return;
@ -453,6 +471,7 @@ public class BukkitPermissions {
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onPluginDisable(PluginDisableEvent event) { public void onPluginDisable(PluginDisableEvent event) {
collectPermissions(); collectPermissions();
// updateAllPlayers(); // updateAllPlayers();
} }

View file

@ -12,227 +12,239 @@ import org.bukkit.entity.Player;
/** /**
* Made by Nijikokun. Changed by Gabriel Couto * Made by Nijikokun. Changed by Gabriel Couto
* *
* This class is intended to *read* permissions from a single world. * This class is intended to *read* permissions from a single world.
* *
* @author Nijikokun * @author Nijikokun
* @author Gabriel Couto * @author Gabriel Couto
* @author ElgarL * @author ElgarL
*/ */
public abstract class PermissionsReaderInterface { public abstract class PermissionsReaderInterface {
/** /**
* *
* @param player * @param player
* @param string * @param string
* @return true if has permission * @return true if has permission
*/ */
public abstract boolean has(Player player, String string); public abstract boolean has(Player player, String string);
/** /**
* *
* @param player * @param player
* @param string * @param string
* @return true if has permission * @return true if has permission
*/ */
public abstract boolean permission(Player player, String string); public abstract boolean permission(Player player, String string);
/** /**
* *
* @param userName * @param userName
* @return group name for this player. * @return group name for this player.
*/ */
public abstract String getGroup(String userName); public abstract String getGroup(String userName);
/** /**
* *
* @param userName * @param userName
* @param groupName * @param groupName
* @return true if in group * @return true if in group
*/ */
public abstract boolean inGroup(String userName, String groupName); public abstract boolean inGroup(String userName, String groupName);
/** /**
* *
* @param groupName * @param groupName
* @return String of prefix * @return String of prefix
*/ */
public abstract String getGroupPrefix(String groupName); public abstract String getGroupPrefix(String groupName);
/** /**
* *
* @param groupName * @param groupName
* @return String of suffix * @return String of suffix
*/ */
public abstract String getGroupSuffix(String groupName); public abstract String getGroupSuffix(String groupName);
/** /**
* *
* @param groupName * @param groupName
* @return true if can build * @return true if can build
*/ */
public abstract boolean canGroupBuild(String groupName); public abstract boolean canGroupBuild(String groupName);
/** /**
* *
* @param groupName * @param groupName
* @param node * @param node
* @return String value * @return String value
*/ */
public abstract String getGroupPermissionString(String groupName, String node); public abstract String getGroupPermissionString(String groupName, String node);
/** /**
* *
* @param groupName * @param groupName
* @param node * @param node
* @return integer value * @return integer value
*/ */
public abstract int getGroupPermissionInteger(String groupName, String node); public abstract int getGroupPermissionInteger(String groupName, String node);
/** /**
* *
* @param groupName * @param groupName
* @param node * @param node
* @return boolean value * @return boolean value
*/ */
public abstract boolean getGroupPermissionBoolean(String groupName, String node); public abstract boolean getGroupPermissionBoolean(String groupName, String node);
/** /**
* *
* @param groupName * @param groupName
* @param node * @param node
* @return double value * @return double value
*/ */
public abstract double getGroupPermissionDouble(String groupName, String node); public abstract double getGroupPermissionDouble(String groupName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return String value * @return String value
*/ */
public abstract String getUserPermissionString(String userName, String node); public abstract String getUserPermissionString(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return integer value * @return integer value
*/ */
public abstract int getUserPermissionInteger(String userName, String node); public abstract int getUserPermissionInteger(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return boolean value * @return boolean value
*/ */
public abstract boolean getUserPermissionBoolean(String userName, String node); public abstract boolean getUserPermissionBoolean(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return double value * @return double value
*/ */
public abstract double getUserPermissionDouble(String userName, String node); public abstract double getUserPermissionDouble(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return String value * @return String value
*/ */
public abstract String getPermissionString(String userName, String node); public abstract String getPermissionString(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return integer value * @return integer value
*/ */
public abstract int getPermissionInteger(String userName, String node); public abstract int getPermissionInteger(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return boolean value * @return boolean value
*/ */
public abstract boolean getPermissionBoolean(String userName, String node); public abstract boolean getPermissionBoolean(String userName, String node);
/** /**
* *
* @param userName * @param userName
* @param node * @param node
* @return double value * @return double value
*/ */
public abstract double getPermissionDouble(String userName, String node); public abstract double getPermissionDouble(String userName, String node);
///////////////////////////// /////////////////////////////
/** /**
* Gets the appropriate prefix for the user. * Gets the appropriate prefix for the user.
* This method is a utility method for chat plugins to get the user's prefix * This method is a utility method for chat plugins to get the user's prefix
* without having to look at every one of the user's ancestors. * without having to look at every one of the user's ancestors.
* Returns an empty string if user has no parent groups. * Returns an empty string if user has no parent groups.
* *
* @param user Player's name * @param user Player's name
* @return Player's prefix * @return Player's prefix
*/ */
public abstract String getUserPrefix(String user); public abstract String getUserPrefix(String user);
/** /**
* Gets the appropriate suffix for the user. * Gets the appropriate suffix for the user.
* This method is a utility method for chat plugins to get the user's suffix * This method is a utility method for chat plugins to get the user's suffix
* without having to look at every one of the user's ancestors. * without having to look at every one of the user's ancestors.
* Returns an empty string if user has no parent groups. * Returns an empty string if user has no parent groups.
* *
* @param user Player's name * @param user Player's name
* @return Player's suffix * @return Player's suffix
*/ */
public abstract String getUserSuffix(String user); public abstract String getUserSuffix(String user);
/** /**
* Returns the group object representing the default group of the given world. * Returns the group object representing the default group of the given
* This method will return null if the object does not exist or the world has no default group. * world.
* @return Group object representing default world, or null if it doesn't exist or is not defined. * This method will return null if the object does not exist or the world
*/ * has no default group.
public abstract Group getDefaultGroup(); *
* @return Group object representing default world, or null if it doesn't
* exist or is not defined.
*/
public abstract Group getDefaultGroup();
/** /**
* Gets a array of the names of all parent groups in the same world. * Gets a array of the names of all parent groups in the same world.
* @param name Target user's name *
* @return An array containing the names of all parent groups (including ancestors) that are in the same world * @param name Target user's name
*/ * @return An array containing the names of all parent groups (including
public abstract String[] getGroups(String name); * ancestors) that are in the same world
*/
public abstract String[] getGroups(String name);
public abstract String getInfoString(String entryName, String path, boolean isGroup); public abstract String getInfoString(String entryName, String path, boolean isGroup);
//public abstract String getInfoString(String entryName, String path, boolean isGroup, Comparator<String> comparator);
public abstract int getInfoInteger(String entryName, String path, boolean isGroup); //public abstract String getInfoString(String entryName, String path, boolean isGroup, Comparator<String> comparator);
//public abstract int getInfoInteger(String entryName, String path, boolean isGroup, Comparator<Integer> comparator);
/** public abstract int getInfoInteger(String entryName, String path, boolean isGroup);
* Gets a double from the Info node without inheritance.
* @param entryName
* @param path
* @param isGroup
* @return -1 if not found
*/
public abstract double getInfoDouble(String entryName, String path, boolean isGroup);
//public abstract double getInfoDouble(String entryName, String path, boolean isGroup, Comparator<Double> comparator);
public abstract boolean getInfoBoolean(String entryName, String path, boolean isGroup); //public abstract int getInfoInteger(String entryName, String path, boolean isGroup, Comparator<Integer> comparator);
//public abstract boolean getInfoBoolean(String entryName, String path, boolean isGroup, Comparator<Boolean> comparator);
public abstract void addUserInfo(String name, String path, Object data); /**
* Gets a double from the Info node without inheritance.
*
* @param entryName
* @param path
* @param isGroup
* @return -1 if not found
*/
public abstract double getInfoDouble(String entryName, String path, boolean isGroup);
public abstract void removeUserInfo(String name, String path); //public abstract double getInfoDouble(String entryName, String path, boolean isGroup, Comparator<Double> comparator);
public abstract void addGroupInfo(String name, String path, Object data); public abstract boolean getInfoBoolean(String entryName, String path, boolean isGroup);
public abstract void removeGroupInfo(String name, String path); //public abstract boolean getInfoBoolean(String entryName, String path, boolean isGroup, Comparator<Boolean> comparator);
//////////////////////////////
public abstract void addUserInfo(String name, String path, Object data);
public abstract void removeUserInfo(String name, String path);
public abstract void addGroupInfo(String name, String path, Object data);
public abstract void removeGroupInfo(String name, String path);
//////////////////////////////
public abstract List<String> getAllPlayersPermissions(String userName); public abstract List<String> getAllPlayersPermissions(String userName);

View file

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

View file

@ -6,47 +6,48 @@ package org.anjocaido.groupmanager.utils;
/** /**
* Just a list of commands for this plugin * Just a list of commands for this plugin
*
* @author gabrielcouto * @author gabrielcouto
*/ */
public enum GroupManagerPermissions { public enum GroupManagerPermissions {
manuadd, manuadd,
manudel, manudel,
manuaddsub, manuaddsub,
manudelsub, manudelsub,
mangadd, mangadd,
mangdel, mangdel,
manuaddp, manuaddp,
manudelp, manudelp,
manulistp, manulistp,
manucheckp, manucheckp,
mangaddp, mangaddp,
mangdelp, mangdelp,
manglistp, manglistp,
mangcheckp, mangcheckp,
mangaddi, mangaddi,
mangdeli, mangdeli,
manuaddv, manuaddv,
manudelv, manudelv,
manulistv, manulistv,
manucheckv, manucheckv,
mangaddv, mangaddv,
mangdelv, mangdelv,
manglistv, manglistv,
mangcheckv, mangcheckv,
manwhois, manwhois,
tempadd, tempadd,
tempdel, tempdel,
templist, templist,
tempdelall, tempdelall,
mansave, mansave,
manload, manload,
listgroups, listgroups,
manpromote, manpromote,
mandemote, mandemote,
mantogglevalidate, mantogglevalidate,
mantogglesave, mantogglesave,
manworld, manworld,
manselect, manselect,
manclear manclear
} }

View file

@ -7,61 +7,61 @@ package org.anjocaido.groupmanager.utils;
import org.anjocaido.groupmanager.data.DataUnit; import org.anjocaido.groupmanager.data.DataUnit;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class PermissionCheckResult { public class PermissionCheckResult {
/** /**
* It should be the owner of the access level found. * It should be the owner of the access level found.
* *
* Use instanceof to find the owner type * Use instanceof to find the owner type
*/ */
public DataUnit owner; public DataUnit owner;
/** /**
* The permission node found in the DataUnit. * The permission node found in the DataUnit.
*/ */
public String accessLevel; public String accessLevel;
/** /**
* The full name of the permission you are looking for * The full name of the permission you are looking for
*/ */
public String askedPermission; public String askedPermission;
/** /**
* The result conclusion of the search. * The result conclusion of the search.
* It determines if the owner can do, or not. * It determines if the owner can do, or not.
* *
* It even determines if it has an owner. * It even determines if it has an owner.
*/ */
public Type resultType = Type.NOTFOUND; public Type resultType = Type.NOTFOUND;
/** /**
* The type of result the search can give. * The type of result the search can give.
*/ */
public enum Type { public enum Type {
/** /**
* If found a matching node starting with '+'. * If found a matching node starting with '+'.
* It means the user CAN do the permission. * It means the user CAN do the permission.
*/ */
EXCEPTION, EXCEPTION,
/** /**
* If found a matching node starting with '-'. * If found a matching node starting with '-'.
* It means the user CANNOT do the permission. * It means the user CANNOT do the permission.
*/ */
NEGATION, NEGATION,
/** /**
* If just found a common matching node. * If just found a common matching node.
* IT means the user CAN do the permission. * IT means the user CAN do the permission.
*/ */
FOUND, FOUND,
/** /**
* If no matchin node was found. * If no matchin node was found.
* It means the user CANNOT do the permission. * It means the user CANNOT do the permission.
* *
* owner field and accessLevel field should not be considered, * owner field and accessLevel field should not be considered,
* when type is * when type is
* NOTFOUND * NOTFOUND
*/ */
NOTFOUND NOTFOUND
} }
} }

View file

@ -7,43 +7,46 @@ package org.anjocaido.groupmanager.utils;
import java.util.Comparator; import java.util.Comparator;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public class StringPermissionComparator implements Comparator<String> { public class StringPermissionComparator implements Comparator<String> {
@Override @Override
public int compare(String permA, String permB) { public int compare(String permA, String permB) {
boolean ap = permA.startsWith("+");
boolean bp = permB.startsWith("+");
boolean am = permA.startsWith("-");
boolean bm = permB.startsWith("-");
if (ap && bp) {
return 0;
}
if (ap && !bp) {
return -1;
}
if (!ap && bp) {
return 1;
}
if (am && bm) {
return 0;
}
if (am && !bm) {
return -1;
}
if (!am && bm) {
return 1;
}
return permA.compareToIgnoreCase(permB);
}
private static StringPermissionComparator instance;
public static StringPermissionComparator getInstance() { boolean ap = permA.startsWith("+");
if (instance == null) { boolean bp = permB.startsWith("+");
instance = new StringPermissionComparator(); boolean am = permA.startsWith("-");
} boolean bm = permB.startsWith("-");
return instance; if (ap && bp) {
} return 0;
}
if (ap && !bp) {
return -1;
}
if (!ap && bp) {
return 1;
}
if (am && bm) {
return 0;
}
if (am && !bm) {
return -1;
}
if (!am && bm) {
return 1;
}
return permA.compareToIgnoreCase(permB);
}
private static StringPermissionComparator instance;
public static StringPermissionComparator getInstance() {
if (instance == null) {
instance = new StringPermissionComparator();
}
return instance;
}
} }

View file

@ -22,13 +22,12 @@ import java.util.List;
import org.anjocaido.groupmanager.GroupManager; import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.data.Group; import org.anjocaido.groupmanager.data.Group;
/** /**
* *
* @author gabrielcouto * @author gabrielcouto
*/ */
public abstract class Tasks { public abstract class Tasks {
/** /**
* Gets the exception stack trace as a string. * Gets the exception stack trace as a string.
* *
@ -36,35 +35,38 @@ public abstract class Tasks {
* @return stack trace as a string * @return stack trace as a string
*/ */
public static String getStackTraceAsString(Exception exception) { public static String getStackTraceAsString(Exception exception) {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw); PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw); exception.printStackTrace(pw);
return sw.toString(); return sw.toString();
} }
public static void copy(InputStream src, File dst) throws IOException { public static void copy(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out InputStream in = src;
byte[] buf = new byte[1024]; OutputStream out = new FileOutputStream(dst);
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
try {
in.close();
} catch (Exception e) {
}
}
public static void copy(File src, File dst) throws IOException { // Transfer bytes from in to out
InputStream in = new FileInputStream(src); byte[] buf = new byte[1024];
copy(in, dst); int len;
} while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
/** }
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 * Appends a string to a file
* *
* @param data * @param data
@ -82,86 +84,92 @@ public abstract class Tasks {
out.append(System.getProperty("line.separator")); out.append(System.getProperty("line.separator"));
out.append(data); out.append(data);
out.append(System.getProperty("line.separator")); out.append(System.getProperty("line.separator"));
out.close(); out.close();
} }
public static void removeOldFiles(GroupManager gm, File folder) { public static void removeOldFiles(GroupManager gm, File folder) {
if (folder.isDirectory()) {
long oldTime = System.currentTimeMillis() - (((long)gm.getGMConfig().getBackupDuration()*60*60)*1000);
for (File olds : folder.listFiles()) {
if (olds.isFile()) {
if (olds.lastModified() < oldTime) {
try {
olds.delete();
} catch (Exception e) {
}
}
}
}
}
}
public static String getDateString() { if (folder.isDirectory()) {
GregorianCalendar now = new GregorianCalendar(); long oldTime = System.currentTimeMillis() - (((long) gm.getGMConfig().getBackupDuration() * 60 * 60) * 1000);
String date = ""; for (File olds : folder.listFiles()) {
date += now.get(Calendar.DAY_OF_MONTH); if (olds.isFile()) {
date += "-"; if (olds.lastModified() < oldTime) {
date += now.get(Calendar.HOUR); try {
date += "-"; olds.delete();
date += now.get(Calendar.MINUTE); } catch (Exception e) {
return date; }
} }
}
}
}
}
public static String getStringListInString(List<String> list) { public static String getDateString() {
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) { GregorianCalendar now = new GregorianCalendar();
if (list == null) { String date = "";
return ""; date += now.get(Calendar.DAY_OF_MONTH);
} date += "-";
String result = ""; date += now.get(Calendar.HOUR);
for (int i = 0; i < list.length; i++) { date += "-";
result += list[i]; date += now.get(Calendar.MINUTE);
if (i < ((list.length) - 1)) { return date;
result += ", "; }
}
}
return result;
}
public static String getGroupListInString(List<Group> list) { public static String getStringListInString(List<String> list) {
if (list == null) {
return ""; if (list == null) {
} return "";
String result = ""; }
for (int i = 0; i < list.size(); i++) { String result = "";
result += list.get(i).getName(); for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) { result += list.get(i);
result += ", "; if (i < list.size() - 1) {
} result += ", ";
} }
return result; }
} return result;
}
public static String join(String[] arr, String separator) {
if (arr.length == 0) public static String getStringArrayInString(String[] list) {
return "";
String out = arr[0].toString(); if (list == null) {
for (int i = 1; i < arr.length; i++) return "";
out += separator + arr[i]; }
return out; String result = "";
} for (int i = 0; i < list.length; i++) {
result += list[i];
if (i < ((list.length) - 1)) {
result += ", ";
}
}
return result;
}
public static String getGroupListInString(List<Group> list) {
if (list == null) {
return "";
}
String result = "";
for (int i = 0; i < list.size(); i++) {
result += list.get(i).getName();
if (i < list.size() - 1) {
result += ", ";
}
}
return result;
}
public static String join(String[] arr, String separator) {
if (arr.length == 0)
return "";
String out = arr[0].toString();
for (int i = 1; i < arr.length; i++)
out += separator + arr[i];
return out;
}
} }