1
0
mirror of https://github.com/essentials/Essentials.git synced 2025-08-19 21:11:25 +02:00

2.1 prerelease, part 2 of 3

git-svn-id: https://svn.java.net/svn/essentials~svn/trunk2.1@1015 e251c2fe-e539-e718-e476-b85c1f46cddb
This commit is contained in:
Zenexer
2011-03-30 04:03:21 +00:00
commit 71c5e8c54e
223 changed files with 28819 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="EssentialsGroupManager" default="default" basedir=".">
<description>Builds, tests, and runs the project EssentialsGroupManager.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="EssentialsGroupManager-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
build.xml.data.CRC32=a6709b83
build.xml.script.CRC32=5b346364
build.xml.stylesheet.CRC32=28e38971@1.38.2.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=a6709b83
nbproject/build-impl.xml.script.CRC32=70ed0f6c
nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45

View File

@@ -0,0 +1 @@
user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties

View File

@@ -0,0 +1,73 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=EssentialsGroupManager
application.vendor=gabrielcouto
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/EssentialsGroupManager.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar
includes=**
jar.compress=false
javac.classpath=\
${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>EssentialsGroupManager</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
</configuration>
</project>

View File

@@ -0,0 +1,14 @@
settings:
data:
save:
minutes: 10
logging:
level: INFO
permission:
world:
mirror:
world1:
- world2
- world3
world4:
- world5

View File

@@ -0,0 +1,172 @@
groups:
Default:
default: true
permissions:
- essentials.help
- essentials.home
- essentials.motd
- essentials.sethome
- essentials.spawn
inheritance: []
info:
prefix: ''
build: false
suffix: ''
SemiAdmin:
default: false
permissions:
- +groupmanager.mandemote
- +groupmanager.manpromote
- -groupmanager.*
- '*'
inheritance:
- moderator
info:
prefix: '&c'
build: true
suffix: SemiAdmin
RedFaction:
default: false
permissions: []
inheritance:
- peasant
info:
prefix: '&c'
roles-category: faction
build: true
suffix: Red
Farmer:
default: false
permissions:
- essentials.kit
- essentials.kit.farmer
- essentials.spawnmob
inheritance: []
info:
roles-requirement:
- BlueFaction
- RedFaction
prefix: ''
roles-category: job
build: false
suffix: ''
Healer:
default: false
permissions:
- essentials.kit
- essentials.kit.healer
- essentials.heal
inheritance: []
info:
roles-requirement:
- BlueFaction
- RedFaction
prefix: ''
roles-category: job
build: false
suffix: ''
Fighter:
default: false
permissions:
- essentials.kit
- essentials.kit.fighter
inheritance: []
info:
prefix: ''
roles-category: skill
build: false
suffix: ''
Admin:
default: false
permissions:
- '*'
inheritance:
- semiadmin
info:
prefix: ''
build: true
suffix: ''
Miner:
default: false
permissions:
- essentials.kit
- essentials.kit.miner
- flashlight.regular
inheritance: []
info:
roles-requirement:
- BlueFaction
- RedFaction
prefix: ''
roles-category: job
build: false
suffix: ''
FlyingMan:
default: false
permissions:
- nocheat.moving
inheritance: []
info:
roles-requirement: Fighter&SuperCart
prefix: ''
roles-category: skill
build: false
suffix: ''
Peasant:
default: false
permissions:
- roles.joinrole
- roles.leaverole
- roles.myroles
inheritance:
- default
info:
prefix: '&e'
build: true
suffix: Peasant
BlueFaction:
default: false
permissions: []
inheritance:
- peasant
info:
prefix: '&d'
roles-category: faction
build: true
suffix: Blue
Railer:
default: false
permissions:
- essentials.kit
- essentials.kit.railer
inheritance: []
info:
roles-requirement: Miner
prefix: ''
roles-category: subjob
build: false
suffix: ''
SuperCart:
default: false
permissions:
- minecartmania.*
inheritance: []
info:
roles-requirement: Railer
prefix: ''
roles-category: skill
build: false
suffix: ''
Moderator:
default: false
permissions:
- essentials.tp
- essentials.tphere
- essentials.item
- essentials.give
inheritance:
- default
info:
prefix: '&c'
build: true
suffix: Mod

View File

@@ -0,0 +1,120 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import org.anjocaido.groupmanager.utils.Tasks;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
/**
*
* @author gabrielcouto
*/
public class GMConfiguration {
private GroupManager plugin;
private Map<String, Object> rootDataNode;
private File configFile;
public GMConfiguration(GroupManager plugin) {
this.plugin = plugin;
load();
}
public void load() {
if (!plugin.getDataFolder().exists()) {
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);
}
}
Yaml yaml = new Yaml(new SafeConstructor());
FileInputStream rx = null;
try {
rx = new FileInputStream(configFile);
} catch (FileNotFoundException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
try {
rootDataNode = (Map<String, Object>) yaml.load(new UnicodeReader(rx));
if (rootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex);
} finally {
try {
rx.close();
} catch (IOException ex) {
}
}
adjustLoggerLevel();
}
public Map<String, Object> getMirrorsMap() {
if (rootDataNode.get("settings") instanceof Map) {
Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings");
if (settingsNode.get("permission") instanceof Map) {
Map<String, Object> permissionNode = (Map<String, Object>) settingsNode.get("permission");
if (permissionNode.get("world") instanceof Map) {
Map<String, Object> worldsNode = (Map<String, Object>) permissionNode.get("world");
if (worldsNode.get("mirror") instanceof Map) {
Map<String, Object> mirrorsNode = (Map<String, Object>) worldsNode.get("mirror");
return mirrorsNode;
}
}
}
}
return null;
}
public Integer getSaveInterval() {
if (rootDataNode.get("settings") instanceof Map) {
Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings");
if (settingsNode.get("data") instanceof Map) {
Map<String, Object> dataNode = (Map<String, Object>) settingsNode.get("data");
if (dataNode.get("save") instanceof Map) {
Map<String, Object> saveNode = (Map<String, Object>) dataNode.get("save");
if (saveNode.get("minutes") instanceof Integer) {
return (Integer) saveNode.get("minutes");
}
}
}
}
return 10;
}
public void adjustLoggerLevel() {
if (rootDataNode.get("settings") instanceof Map) {
Map<String, Object> settingsNode = (Map<String, Object>) rootDataNode.get("settings");
if (settingsNode.get("logging") instanceof Map) {
Map<String, Object> loggingNode = (Map<String, Object>) settingsNode.get("logging");
if (loggingNode.get("level") instanceof String) {
String level = (String) loggingNode.get("level");
try {
GroupManager.logger.setLevel(Level.parse(level));
return;
} catch (Exception e) {
}
}
}
}
GroupManager.logger.setLevel(Level.INFO);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,114 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import java.util.ArrayList;
import java.util.Collections;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.utils.StringPermissionComparator;
/**
*
* @author gabrielcouto
*/
public abstract class DataUnit {
private WorldDataHolder dataSource;
private String name;
private boolean changed;
private ArrayList<String> permissions = new ArrayList<String>();
public DataUnit(WorldDataHolder dataSource, String name) {
this.dataSource = dataSource;
this.name = name;
}
/**
* Every group is matched only by their names and DataSources names.
* @param o
* @return true if they are equal. false if not.
*/
@Override
public boolean equals(Object o) {
if (o instanceof DataUnit) {
DataUnit go = (DataUnit) o;
if (this.getName().equalsIgnoreCase(go.getName()) && this.dataSource.getName().equalsIgnoreCase(go.getDataSource().getName())) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0);
return hash;
}
/**
* @return the dataSource
*/
public WorldDataHolder getDataSource() {
return dataSource;
}
/**
* @return the name
*/
public String getName() {
return name;
}
public void flagAsChanged() {
GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - DataUnit: "+getName()+" flagged as changed!");
// for(StackTraceElement st: Thread.currentThread().getStackTrace()){
// GroupManager.logger.finest(st.toString());
// }
changed = true;
}
public boolean isChanged() {
return changed;
}
public void flagAsSaved() {
GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - 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 ArrayList<String> getPermissionList() {
return (ArrayList<String>) permissions.clone();
}
public void sortPermissions(){
Collections.sort(permissions, StringPermissionComparator.getInstance());
}
}

View File

@@ -0,0 +1,122 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import java.util.ArrayList;
import java.util.Map;
/**
*
* @author gabrielcouto
*/
public class Group extends DataUnit implements Cloneable {
/**
* The group it inherits DIRECTLY!
*/
private ArrayList<String> inherits = new ArrayList<String>();
/**
*This one holds the fields in INFO node.
* like prefix = 'c'
* or build = false
*/
private GroupVariables variables = new GroupVariables(this);
/**
*
* @param name
*/
public Group(WorldDataHolder source, String name) {
super(source,name);
}
/**
* Clone this group
* @return a clone of this group
*/
@Override
public Group clone() {
Group clone = new Group(getDataSource(), this.getName());
clone.inherits = ((ArrayList<String>) this.getInherits().clone());
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
*/
public Group clone(WorldDataHolder dataSource) {
if (dataSource.groupExists(this.getName())) {
return null;
}
Group clone = getDataSource().createGroup(this.getName());
clone.inherits = ((ArrayList<String>) this.getInherits().clone());
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;
}
/**
* a COPY of inherits list
* You can't manage the list by here
* Lol... version 0.6 had a problem because this.
* @return the inherits
*/
public ArrayList<String> getInherits() {
return (ArrayList<String>) inherits.clone();
}
/**
* @param inherits the inherits to set
*/
public void addInherits(Group inherit) {
if (!this.getDataSource().groupExists(inherit.getName())) {
getDataSource().addGroup(inherit);
}
if (!inherits.contains(inherit.getName().toLowerCase())) {
inherits.add(inherit.getName().toLowerCase());
}
flagAsChanged();
}
public boolean removeInherits(String inherit) {
if (this.inherits.contains(inherit.toLowerCase())) {
this.inherits.remove(inherit.toLowerCase());
flagAsChanged();
return true;
}
return false;
}
/**
* @return the variables
*/
public GroupVariables getVariables() {
return variables;
}
/**
*
* @param varList
*/
public void setVariables(Map<String, Object> varList) {
GroupVariables temp = new GroupVariables(this, varList);
variables.clearVars();
for(String key: temp.getVarKeyList()){
variables.addVar(key, temp.getVarObject(key));
}
flagAsChanged();
}
}

View File

@@ -0,0 +1,87 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import java.util.Map;
/**
*
* @author gabrielcouto
*/
public class GroupVariables extends Variables implements Cloneable {
private 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);
variables = varList;
if (variables.get("prefix") == null) {
variables.put("prefix", "");
owner.flagAsChanged();
}
//thisGrp.prefix = infoNode.get("prefix").toString();
if (variables.get("suffix") == null) {
variables.put("suffix", "");
owner.flagAsChanged();
}
//thisGrp.suffix = infoNode.get("suffix").toString();
if (variables.get("build") == null) {
variables.put("build", false);
owner.flagAsChanged();
}
this.owner = owner;
}
/**
* A clone of all vars here.
* @return
*/
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

@@ -0,0 +1,187 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import com.sun.org.apache.bcel.internal.generic.AALOAD;
import java.util.ArrayList;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import java.util.Map;
/**
*
* @author gabrielcouto
*/
public class User extends DataUnit implements Cloneable {
/**
*
*/
private String group = null;
private ArrayList<String> subGroups = new ArrayList<String>();
/**
*This one holds the fields in INFO node.
* like prefix = 'c'
* or build = false
*/
private UserVariables variables = new UserVariables(this);
/**
*
* @param name
*/
public User(WorldDataHolder source, String name) {
super(source,name);
this.group = source.getDefaultGroup().getName();
}
/**
*
* @return
*/
@Override
public User clone() {
User clone = new User(getDataSource(), this.getName());
clone.group = this.group;
for(String perm: this.getPermissionList()){
clone.addPermission(perm);
}
//clone.variables = this.variables.clone();
//clone.flagAsChanged();
return clone;
}
/**
* Use this to deliver a user from one WorldDataHolder to another
* @param dataSource
* @return null if given dataSource already contains the same user
*/
public User clone(WorldDataHolder dataSource) {
if (dataSource.isUserDeclared(this.getName())) {
return null;
}
User clone = dataSource.createUser(this.getName());
if (dataSource.getGroup(group) == null) {
clone.setGroup(dataSource.getDefaultGroup());
} else {
clone.setGroup(this.getGroupName());
}
for(String perm: this.getPermissionList()){
clone.addPermission(perm);
}
//clone.variables = this.variables.clone();
clone.flagAsChanged();
return clone;
}
public Group getGroup() {
Group result = getDataSource().getGroup(group);
if (result == null) {
this.setGroup(getDataSource().getDefaultGroup());
result = getDataSource().getDefaultGroup();
}
return result;
}
/**
* @return the group
*/
public String getGroupName() {
Group result = getDataSource().getGroup(group);
if (result == null) {
group = getDataSource().getDefaultGroup().getName();
}
return group;
}
/**
* @param group the group to set
*/
@Deprecated
public void setGroup(String group) {
this.group = group;
flagAsChanged();
}
/**
* @param group the group to set
*/
public void setGroup(Group group) {
if (!this.getDataSource().groupExists(group.getName())) {
getDataSource().addGroup(group);
}
group = getDataSource().getGroup(group.getName());
this.group = group.getName();
flagAsChanged();
}
public void addSubGroup(Group subGroup){
if(this.group.equalsIgnoreCase(subGroup.getName())){
return;
}
if (!this.getDataSource().groupExists(subGroup.getName())) {
getDataSource().addGroup(subGroup);
}
subGroup = getDataSource().getGroup(subGroup.getName());
removeSubGroup(subGroup);
subGroups.add(subGroup.getName());
flagAsChanged();
}
public int subGroupsSize(){
return subGroups.size();
}
public boolean isSubGroupsEmpty(){
return subGroups.isEmpty();
}
public boolean containsSubGroup(Group subGroup){
return subGroups.contains(subGroup.getName());
}
public boolean removeSubGroup(Group subGroup){
try{
if(subGroups.remove(subGroup.getName())){
flagAsChanged();
return true;
}
} catch (Exception e){
}
return false;
}
public ArrayList<Group> subGroupListCopy(){
ArrayList<Group> val = new ArrayList<Group>();
for(String gstr: subGroups){
Group g = getDataSource().getGroup(gstr);
if(g==null){
removeSubGroup(g);
continue;
}
val.add(g);
}
return val;
}
public ArrayList<String> subGroupListStringCopy(){
return (ArrayList<String>) subGroups.clone();
}
/**
* @return the variables
*/
public UserVariables getVariables() {
return variables;
}
/**
*
* @param varList
*/
public void setVariables(Map<String, Object> varList) {
UserVariables temp = new UserVariables(this, varList);
variables.clearVars();
for(String key: temp.getVarKeyList()){
variables.addVar(key, temp.getVarObject(key));
}
flagAsChanged();
}
}

View File

@@ -0,0 +1,45 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import java.util.Map;
/**
*
* @author gabrielcouto
*/
public class UserVariables extends Variables{
private User owner;
public UserVariables(User owner){
super(owner);
this.owner = owner;
}
public UserVariables(User owner, Map<String, Object> varList) {
super(owner);
this.variables = varList;
this.owner = owner;
}
/**
* A clone of all vars here.
* @return
*/
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

@@ -0,0 +1,192 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.data;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*A class that holds variables of a user/group.
* In groups, it holds the contents of INFO node.
* Like:
* prefix
* suffix
* build
*
* @author gabrielcouto
*/
public abstract class Variables implements Cloneable {
private DataUnit owner;
protected Map<String, Object> variables = new HashMap<String, Object>();
public Variables(DataUnit 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
* @param name
* @return a Object if exists. null if doesn't exists
*/
public Object getVarObject(String name) {
return variables.get(name);
}
/**
* Get the String value for the given var name
* @param name the var key name
* @return "" if null. or the toString() value of object
*/
public String getVarString(String name) {
Object o = variables.get(name);
try {
return o == null ? "" : o.toString();
} catch (Exception e) {
return "";
}
}
/**
*
* @param name
* @return false if null. or a Boolean.parseBoolean of the string
*/
public Boolean getVarBoolean(String name) {
Object o = variables.get(name);
try {
return o == null ? false : Boolean.parseBoolean(o.toString());
} catch (Exception e) {
return false;
}
}
/**
*
* @param name
* @return -1 if null. or a parseInt of the string
*/
public Integer getVarInteger(String name) {
Object o = variables.get(name);
try {
return o == null ? -1 : Integer.parseInt(o.toString());
} catch (Exception e) {
return -1;
}
}
/**
*
* @param name
* @return -1 if null. or a parseDouble of the string
*/
public Double getVarDouble(String name) {
Object o = variables.get(name);
try {
return o == null ? -1.0D : Double.parseDouble(o.toString());
} catch (Exception e) {
return -1.0D;
}
}
/**
* All variable keys this is holding
* @return
*/
public Set<String> getVarKeyList() {
return variables.keySet();
}
/**
* 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

@@ -0,0 +1,204 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.dataholder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.anjocaido.groupmanager.data.User;
/**
*
* @author gabrielcouto
*/
public class OverloadedWorldHolder extends WorldDataHolder {
/**
*
*/
protected Map<String, User> overloadedUsers = new HashMap<String, User>();
/**
*
* @param ph
*/
public OverloadedWorldHolder(WorldDataHolder ph) {
super(ph.getName());
this.f = ph.f;
this.groupsFile = ph.groupsFile;
this.usersFile = ph.usersFile;
this.defaultGroup = ph.defaultGroup;
this.groups = ph.groups;
this.users = ph.users;
}
/**
*
* @param userName
* @return
*/
@Override
public User getUser(String userName) {
//OVERLOADED CODE
if (overloadedUsers.containsKey(userName.toLowerCase())) {
return overloadedUsers.get(userName.toLowerCase());
}
//END CODE
if (users.containsKey(userName.toLowerCase())) {
return users.get(userName.toLowerCase());
}
User newUser = createUser(userName);
haveUsersChanged = true;
return newUser;
}
/**
*
* @param theUser
*/
@Override
public void addUser(User theUser) {
if (theUser.getDataSource() != this) {
theUser = theUser.clone(this);
}
if (theUser == null) {
return;
}
if ((theUser.getGroup() == null) || (!groups.containsKey(theUser.getGroupName().toLowerCase()))) {
theUser.setGroup(defaultGroup);
}
//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());
users.put(theUser.getName().toLowerCase(), theUser);
haveUsersChanged = true;
}
/**
*
* @param userName
* @return
*/
@Override
public boolean removeUser(String userName) {
//OVERLOADED CODE
if (overloadedUsers.containsKey(userName.toLowerCase())) {
overloadedUsers.remove(userName.toLowerCase());
return true;
}
//END CODE
if (users.containsKey(userName.toLowerCase())) {
users.remove(userName.toLowerCase());
haveUsersChanged = true;
return true;
}
return false;
}
@Override
public boolean removeGroup(String groupName) {
if (groupName.equals(defaultGroup)) {
return false;
}
for (String key : groups.keySet()) {
if (groupName.equalsIgnoreCase(key)) {
groups.remove(key);
for (String userKey : users.keySet()) {
User user = users.get(userKey);
if (user.getGroupName().equalsIgnoreCase(key)) {
user.setGroup(defaultGroup);
}
}
//OVERLOADED CODE
for (String userKey : overloadedUsers.keySet()) {
User user = overloadedUsers.get(userKey);
if (user.getGroupName().equalsIgnoreCase(key)) {
user.setGroup(defaultGroup);
}
}
//END OVERLOAD
haveGroupsChanged = true;
return true;
}
}
return false;
}
/**
*
* @return
*/
@Override
public Collection<User> getUserList() {
Collection<User> overloadedList = new ArrayList<User>();
Collection<User> normalList = users.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
*/
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
*/
public User surpassOverload(String userName) {
if (!isOverloaded(userName)) {
return getUser(userName);
}
if (users.containsKey(userName.toLowerCase())) {
return users.get(userName.toLowerCase());
}
User newUser = createUser(userName);
return newUser;
}
}

View File

@@ -0,0 +1,939 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.dataholder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.data.Group;
import org.anjocaido.groupmanager.data.User;
import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;
/**
*
* @author gabrielcouto
*/
public class WorldDataHolder {
/**
*
*/
protected String name;
/**
* The actual groups holder
*/
protected Map<String, Group> groups = new HashMap<String, Group>();
/**
* The actual users holder
*/
protected Map<String, User> users = new HashMap<String, User>();
/**
* Points to the default group
*/
protected Group defaultGroup = null;
/**
* The file, which this class loads/save data from/to
* @deprecated
*/
@Deprecated
protected File f;
/**
*
*/
protected AnjoPermissionsHandler permissionsHandler;
/**
*
*/
protected File usersFile;
/**
*
*/
protected File groupsFile;
/**
*
*/
protected boolean haveUsersChanged = false;
/**
*
*/
protected boolean haveGroupsChanged = false;
/**
* Prevent direct instantiation
* @param worldName
*/
protected WorldDataHolder(String worldName) {
name = worldName;
}
/**
* The main constructor for a new WorldDataHolder
* Please don't set the default group as null
* @param worldName
* @param defaultGroup the default group. its good to start with one
*/
public WorldDataHolder(String worldName, Group defaultGroup) {
this.name = worldName;
groups.put(defaultGroup.getName().toLowerCase(), defaultGroup);
this.defaultGroup = defaultGroup;
}
/**
* Search for a user. If it doesn't exist, create a new one with
* default group.
*
* @param userName the name of the user
* @return class that manage that user permission
*/
public User getUser(String userName) {
if (users.containsKey(userName.toLowerCase())) {
return users.get(userName.toLowerCase());
}
User newUser = createUser(userName);
return newUser;
}
/**
* Add a user to the list. If it already exists, overwrite the old.
* @param theUser the user you want to add to the permission list
*/
public void addUser(User theUser) {
if (theUser.getDataSource() != this) {
theUser = theUser.clone(this);
}
if (theUser == null) {
return;
}
if ((theUser.getGroup() == null)) {
theUser.setGroup(defaultGroup);
}
removeUser(theUser.getName());
users.put(theUser.getName().toLowerCase(), theUser);
haveUsersChanged = true;
}
/**
* Removes the user from the list. (he might become a default user)
* @param userName the username from the user to remove
* @return true if it had something to remove
*/
public boolean removeUser(String userName) {
if (users.containsKey(userName.toLowerCase())) {
users.remove(userName.toLowerCase());
haveUsersChanged = true;
return true;
}
return false;
}
/**
*
* @param userName
* @return
*/
public boolean isUserDeclared(String userName) {
return users.containsKey(userName.toLowerCase());
}
/**
* Change the default group of the file.
* @param group the group you want make default.
*/
public void setDefaultGroup(Group group) {
if (!groups.containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) {
addGroup(group);
}
defaultGroup = this.getGroup(group.getName());
haveGroupsChanged = true;
}
/**
* Returns the default group of the file
* @return the default group
*/
public Group getDefaultGroup() {
return defaultGroup;
}
/**
* Returns a group of the given name
* @param groupName the name of the group
* @return a group if it is found. null if not found.
*/
public Group getGroup(String groupName) {
return groups.get(groupName.toLowerCase());
}
/**
* Check if a group exists.
* Its the same of getGroup, but check if it is null.
* @param groupName the name of the group
* @return true if exists. false if not.
*/
public boolean groupExists(String groupName) {
return groups.containsKey(groupName.toLowerCase());
}
/**
* Add a group to the list
* @param groupToAdd
*/
public void addGroup(Group groupToAdd) {
if (groupToAdd.getDataSource() != this) {
groupToAdd = groupToAdd.clone(this);
}
removeGroup(groupToAdd.getName());
groups.put(groupToAdd.getName().toLowerCase(), groupToAdd);
haveGroupsChanged = true;
}
/**
* Remove the group to the list
* @param groupName
* @return true if had something to remove. false the group was default or non-existant
*/
public boolean removeGroup(String groupName) {
if (defaultGroup != null && groupName.equalsIgnoreCase(defaultGroup.getName())) {
return false;
}
if (groups.containsKey(groupName.toLowerCase())) {
groups.remove(groupName.toLowerCase());
haveGroupsChanged = true;
return true;
}
return false;
}
/**
* Creates a new User with the given name
* and adds it to this holder.
* @param userName the username you want
* @return null if user already exists. or new User
*/
public User createUser(String userName) {
if (this.users.containsKey(userName.toLowerCase())) {
return null;
}
User newUser = new User(this, userName);
newUser.setGroup(defaultGroup);
this.addUser(newUser);
haveUsersChanged = true;
return newUser;
}
/**
* Creates a new Group with the given name
* and adds it to this holder
* @param groupName the groupname you want
* @return null if group already exists. or new Group
*/
public Group createGroup(String groupName) {
if (this.groups.containsKey(groupName.toLowerCase())) {
return null;
}
Group newGroup = new Group(this, groupName);
this.addGroup(newGroup);
haveGroupsChanged = true;
return newGroup;
}
/**
*
* @return a collection of the groups
*/
public Collection<Group> getGroupList() {
return groups.values();
}
/**
*
* @return a collection of the users
*/
public Collection<User> getUserList() {
return users.values();
}
/**
* reads the file again
*/
public void reload() {
try {
WorldDataHolder ph = load(this.getName(), getGroupsFile(), getUsersFile());
this.defaultGroup = ph.defaultGroup;
this.groups = ph.groups;
this.users = ph.users;
} catch (Exception ex) {
Logger.getLogger(WorldDataHolder.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Save by yourself!
* @deprecated
*/
@Deprecated
public void commit() {
writeGroups(this, getGroupsFile());
writeUsers(this, getUsersFile());
}
/**
* Returns a data holder for the given file
* @param worldName
* @param file
* @return
* @throws Exception
* @deprecated
*/
@Deprecated
public static WorldDataHolder load(String worldName, File file) throws Exception {
WorldDataHolder ph = new WorldDataHolder(worldName);
ph.f = file;
final Yaml yaml = new Yaml(new SafeConstructor());
Map<String, Object> rootDataNode;
if (!file.exists()) {
throw new Exception("The file which should contain permissions does not exist!\n" + file.getPath());
}
FileInputStream rx = new FileInputStream(file);
try {
rootDataNode = (Map<String, Object>) yaml.load(new UnicodeReader(rx));
if (rootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new Exception("The following file couldn't pass on Parser.\n" + file.getPath(), ex);
} finally {
rx.close();
}
Map<String, List<String>> inheritance = new HashMap<String, List<String>>();
try {
Map<String, Object> allGroupsNode = (Map<String, Object>) rootDataNode.get("groups");
for (String groupKey : allGroupsNode.keySet()) {
Map<String, Object> thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey);
Group thisGrp = ph.createGroup(groupKey);
if (thisGrp == null) {
throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey);
}
if (thisGroupNode.get("default") == null) {
thisGroupNode.put("default", false);
}
if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) {
if (ph.getDefaultGroup() != null) {
GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was.");
GroupManager.logger.warning("Overriding first request.");
}
ph.setDefaultGroup(thisGrp);
}
//PERMISSIONS NODE
if (thisGroupNode.get("permissions") == null) {
thisGroupNode.put("permissions", new ArrayList<String>());
}
if (thisGroupNode.get("permissions") instanceof List) {
for (Object o : ((List) thisGroupNode.get("permissions"))) {
thisGrp.addPermission(o.toString());
}
} else if (thisGroupNode.get("permissions") instanceof String) {
thisGrp.addPermission((String) thisGroupNode.get("permissions"));
} else {
throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List<String>): " + thisGroupNode.get("permissions").getClass().getName());
}
//INFO NODE
Map<String, Object> infoNode = (Map<String, Object>) thisGroupNode.get("info");
if (infoNode != null) {
thisGrp.setVariables(infoNode);
}
//END INFO NODE
Object inheritNode = thisGroupNode.get("inheritance");
if (inheritNode == null) {
thisGroupNode.put("inheritance", new ArrayList<String>());
} else if (inheritNode instanceof List) {
List<String> groupsInh = (List<String>) inheritNode;
for (String grp : groupsInh) {
if (inheritance.get(groupKey) == null) {
List<String> thisInherits = new ArrayList<String>();
inheritance.put(groupKey, thisInherits);
}
inheritance.get(groupKey).add(grp);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("Your Permissions config file is invalid. See console for details.");
}
if (ph.defaultGroup == null) {
throw new IllegalArgumentException("There was no Default Group declared.");
}
for (String groupKey : inheritance.keySet()) {
List<String> inheritedList = inheritance.get(groupKey);
Group thisGroup = ph.getGroup(groupKey);
for (String inheritedKey : inheritedList) {
Group inheritedGroup = ph.getGroup(inheritedKey);
if (thisGroup != null && inheritedGroup != null) {
thisGroup.addInherits(inheritedGroup);
}
}
}
// Process USERS
Map<String, Object> allUsersNode = (Map<String, Object>) rootDataNode.get("users");
for (String usersKey : allUsersNode.keySet()) {
Map<String, Object> thisUserNode = (Map<String, Object>) allUsersNode.get(usersKey);
User thisUser = ph.createUser(usersKey);
if (thisUser == null) {
throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey);
}
if (thisUserNode.get("permissions") == null) {
thisUserNode.put("permissions", new ArrayList<String>());
}
if (thisUserNode.get("permissions") instanceof List) {
for (Object o : ((List) thisUserNode.get("permissions"))) {
thisUser.addPermission(o.toString());
}
} else if (thisUserNode.get("permissions") instanceof String) {
thisUser.addPermission(thisUserNode.get("permissions").toString());
}
//USER INFO NODE - BETA
//INFO NODE
Map<String, Object> infoNode = (Map<String, Object>) thisUserNode.get("info");
if (infoNode != null) {
thisUser.setVariables(infoNode);
}
//END INFO NODE - BETA
if (thisUserNode.get("group") != null) {
Group hisGroup = ph.getGroup(thisUserNode.get("group").toString());
if (hisGroup == null) {
throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName());
}
thisUser.setGroup(hisGroup);
} else {
thisUser.setGroup(ph.defaultGroup);
}
}
return ph;
}
/**
* Returns a data holder for the given file
* @param worldName
* @param groupsFile
* @param usersFile
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static WorldDataHolder load(String worldName, File groupsFile, File usersFile) throws FileNotFoundException, IOException {
WorldDataHolder ph = new WorldDataHolder(worldName);
ph.groupsFile = groupsFile;
ph.usersFile = usersFile;
//READ GROUPS FILE
Yaml yamlGroups = new Yaml(new SafeConstructor());
Map<String, Object> groupsRootDataNode;
if (!groupsFile.exists()) {
throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath());
}
FileInputStream groupsInputStream = new FileInputStream(groupsFile);
try {
groupsRootDataNode = (Map<String, Object>) yamlGroups.load(new UnicodeReader(groupsInputStream));
if (groupsRootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex);
} finally {
groupsInputStream.close();
}
//PROCESS GROUPS FILE
Map<String, List<String>> inheritance = new HashMap<String, List<String>>();
try {
Map<String, Object> allGroupsNode = (Map<String, Object>) groupsRootDataNode.get("groups");
for (String groupKey : allGroupsNode.keySet()) {
Map<String, Object> thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey);
Group thisGrp = ph.createGroup(groupKey);
if (thisGrp == null) {
throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey);
}
if (thisGroupNode.get("default") == null) {
thisGroupNode.put("default", false);
}
if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) {
if (ph.getDefaultGroup() != null) {
GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was.");
GroupManager.logger.warning("Overriding first request.");
}
ph.setDefaultGroup(thisGrp);
}
//PERMISSIONS NODE
if (thisGroupNode.get("permissions") == null) {
thisGroupNode.put("permissions", new ArrayList<String>());
}
if (thisGroupNode.get("permissions") instanceof List) {
for (Object o : ((List) thisGroupNode.get("permissions"))) {
thisGrp.addPermission(o.toString());
}
} else if (thisGroupNode.get("permissions") instanceof String) {
thisGrp.addPermission((String) thisGroupNode.get("permissions"));
} else {
throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List<String>): " + thisGroupNode.get("permissions").getClass().getName());
}
//INFO NODE
Map<String, Object> infoNode = (Map<String, Object>) thisGroupNode.get("info");
if (infoNode != null) {
thisGrp.setVariables(infoNode);
}
//END INFO NODE
Object inheritNode = thisGroupNode.get("inheritance");
if (inheritNode == null) {
thisGroupNode.put("inheritance", new ArrayList<String>());
} else if (inheritNode instanceof List) {
List<String> groupsInh = (List<String>) inheritNode;
for (String grp : groupsInh) {
if (inheritance.get(groupKey) == null) {
List<String> thisInherits = new ArrayList<String>();
inheritance.put(groupKey, thisInherits);
}
inheritance.get(groupKey).add(grp);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException("Your Permissions config file is invalid. See console for details.");
}
if (ph.defaultGroup == null) {
throw new IllegalArgumentException("There was no Default Group declared.");
}
for (String groupKey : inheritance.keySet()) {
List<String> inheritedList = inheritance.get(groupKey);
Group thisGroup = ph.getGroup(groupKey);
for (String inheritedKey : inheritedList) {
Group inheritedGroup = ph.getGroup(inheritedKey);
if (thisGroup != null && inheritedGroup != null) {
thisGroup.addInherits(inheritedGroup);
}
}
}
//READ USERS FILE
Yaml yamlUsers = new Yaml(new SafeConstructor());
Map<String, Object> usersRootDataNode;
if (!groupsFile.exists()) {
throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath());
}
FileInputStream usersInputStream = new FileInputStream(usersFile);
try {
usersRootDataNode = (Map<String, Object>) yamlUsers.load(new UnicodeReader(usersInputStream));
if (usersRootDataNode == null) {
throw new NullPointerException();
}
} catch (Exception ex) {
throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex);
} finally {
usersInputStream.close();
}
// PROCESS USERS FILE
Map<String, Object> allUsersNode = (Map<String, Object>) usersRootDataNode.get("users");
for (String usersKey : allUsersNode.keySet()) {
Map<String, Object> thisUserNode = (Map<String, Object>) allUsersNode.get(usersKey);
User thisUser = ph.createUser(usersKey);
if (thisUser == null) {
throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey);
}
if (thisUserNode.get("permissions") == null) {
thisUserNode.put("permissions", new ArrayList<String>());
}
if (thisUserNode.get("permissions") instanceof List) {
for (Object o : ((List) thisUserNode.get("permissions"))) {
thisUser.addPermission(o.toString());
}
} else if (thisUserNode.get("permissions") instanceof String) {
thisUser.addPermission(thisUserNode.get("permissions").toString());
}
//SUBGROUPS LOADING
if (thisUserNode.get("subgroups") == null) {
thisUserNode.put("subgroups", new ArrayList<String>());
}
if (thisUserNode.get("subgroups") instanceof List) {
for (Object o : ((List) thisUserNode.get("subgroups"))) {
Group subGrp = ph.getGroup(o.toString());
if (subGrp != null) {
thisUser.addSubGroup(subGrp);
} else {
GroupManager.logger.warning("Subgroup " + o.toString() + " not found for user " + thisUser.getName() + ". Ignoring entry.");
}
}
} else if (thisUserNode.get("subgroups") instanceof String) {
Group subGrp = ph.getGroup(thisUserNode.get("subgroups").toString());
if (subGrp != null) {
thisUser.addSubGroup(subGrp);
} else {
GroupManager.logger.warning("Subgroup " + thisUserNode.get("subgroups").toString() + " not found for user " + thisUser.getName() + ". Ignoring entry.");
}
}
//USER INFO NODE - BETA
//INFO NODE
Map<String, Object> infoNode = (Map<String, Object>) thisUserNode.get("info");
if (infoNode != null) {
thisUser.setVariables(infoNode);
}
//END INFO NODE - BETA
if (thisUserNode.get("group") != null) {
Group hisGroup = ph.getGroup(thisUserNode.get("group").toString());
if (hisGroup == null) {
throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName());
}
thisUser.setGroup(hisGroup);
} else {
thisUser.setGroup(ph.defaultGroup);
}
}
return ph;
}
/**
* Write a dataHolder in a specified file
* @param ph
* @param file
* @deprecated
*/
@Deprecated
public static void write(WorldDataHolder ph, File file) {
Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> pluginMap = new HashMap<String, Object>();
root.put("plugin", pluginMap);
Map<String, Object> permissionsMap = new HashMap<String, Object>();
pluginMap.put("permissions", permissionsMap);
permissionsMap.put("system", "default");
Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap);
for (String groupKey : ph.groups.keySet()) {
Group group = ph.groups.get(groupKey);
Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap);
aGroupMap.put("default", group.equals(ph.defaultGroup));
Map<String, Object> infoMap = new HashMap<String, Object>();
aGroupMap.put("info", infoMap);
for (String infoKey : group.getVariables().getVarKeyList()) {
infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
}
aGroupMap.put("inheritance", group.getInherits());
aGroupMap.put("permissions", group.getPermissionList());
}
Map<String, Object> usersMap = new HashMap<String, Object>();
root.put("users", usersMap);
for (String userKey : ph.users.keySet()) {
User user = ph.users.get(userKey);
if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty()) {
continue;
}
Map<String, Object> aUserMap = new HashMap<String, Object>();
usersMap.put(user.getName(), aUserMap);
if (user.getGroup() == null) {
aUserMap.put("group", ph.defaultGroup.getName());
} else {
aUserMap.put("group", user.getGroup().getName());
}
//USER INFO NODE - BETA
if (user.getVariables().getSize() > 0) {
Map<String, Object> infoMap = new HashMap<String, Object>();
aUserMap.put("info", infoMap);
for (String infoKey : user.getVariables().getVarKeyList()) {
infoMap.put(infoKey, user.getVariables().getVarObject(infoKey));
}
}
//END USER INFO NODE - BETA
aUserMap.put("permissions", user.getPermissionList());
}
DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt);
FileWriter tx = null;
try {
tx = new FileWriter(file, false);
tx.write(yaml.dump(root));
tx.flush();
} catch (Exception e) {
} finally {
try {
tx.close();
} catch (IOException ex) {
}
}
}
/**
* Write a dataHolder in a specified file
* @param ph
* @param groupsFile
*/
public static void writeGroups(WorldDataHolder ph, File groupsFile) {
Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> groupsMap = new HashMap<String, Object>();
root.put("groups", groupsMap);
for (String groupKey : ph.groups.keySet()) {
Group group = ph.groups.get(groupKey);
Map<String, Object> aGroupMap = new HashMap<String, Object>();
groupsMap.put(group.getName(), aGroupMap);
if (ph.defaultGroup == null) {
GroupManager.logger.severe("There is no default group for world: " + ph.getName());
}
aGroupMap.put("default", group.equals(ph.defaultGroup));
Map<String, Object> infoMap = new HashMap<String, Object>();
aGroupMap.put("info", infoMap);
for (String infoKey : group.getVariables().getVarKeyList()) {
infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
}
aGroupMap.put("inheritance", group.getInherits());
aGroupMap.put("permissions", group.getPermissionList());
}
DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt);
FileWriter tx = null;
try {
tx = new FileWriter(groupsFile, false);
tx.write(yaml.dump(root));
tx.flush();
} catch (Exception e) {
} finally {
try {
tx.close();
} catch (IOException ex) {
}
}
}
/**
* Write a dataHolder in a specified file
* @param ph
* @param usersFile
*/
public static void writeUsers(WorldDataHolder ph, File usersFile) {
Map<String, Object> root = new HashMap<String, Object>();
Map<String, Object> usersMap = new HashMap<String, Object>();
root.put("users", usersMap);
for (String userKey : ph.users.keySet()) {
User user = ph.users.get(userKey);
if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) {
continue;
}
Map<String, Object> aUserMap = new HashMap<String, Object>();
usersMap.put(user.getName(), aUserMap);
if (user.getGroup() == null) {
aUserMap.put("group", ph.defaultGroup.getName());
} else {
aUserMap.put("group", user.getGroup().getName());
}
//USER INFO NODE - BETA
if (user.getVariables().getSize() > 0) {
Map<String, Object> infoMap = new HashMap<String, Object>();
aUserMap.put("info", infoMap);
for (String infoKey : user.getVariables().getVarKeyList()) {
infoMap.put(infoKey, user.getVariables().getVarObject(infoKey));
}
}
//END USER INFO NODE - BETA
aUserMap.put("permissions", user.getPermissionList());
//SUBGROUPS NODE - BETA
aUserMap.put("subgroups", user.subGroupListStringCopy());
//END SUBGROUPS NODE - BETA
}
DumperOptions opt = new DumperOptions();
opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(opt);
FileWriter tx = null;
try {
tx = new FileWriter(usersFile, false);
tx.write(yaml.dump(root));
tx.flush();
} catch (Exception e) {
} finally {
try {
tx.close();
} catch (IOException ex) {
}
}
}
/**
* Don't use this. Unless you want to make this plugin to interact with original Nijikokun Permissions
* This method is supposed to make the original one reload the file, and propagate the changes made here.
*
* Prefer to use the AnjoCaido's fake version of Nijikokun's Permission plugin.
* The AnjoCaido's Permission can propagate the changes made on this plugin instantly,
* without need to save the file.
*
* @param server the server that holds the plugin
* @deprecated it is not used anymore... unless if you use original Permissions
*/
@Deprecated
public static void reloadOldPlugins(Server server) {
// Only reload permissions
PluginManager pm = server.getPluginManager();
Plugin[] plugins = pm.getPlugins();
for (int i = 0; i < plugins.length; i++) {
plugins[i].getConfiguration().load();
try {
plugins[i].getClass().getMethod("setupPermissions").invoke(plugins[i]);
} catch (Exception ex) {
continue;
}
}
}
/**
* @return the permissionsHandler
*/
public AnjoPermissionsHandler getPermissionsHandler() {
if (permissionsHandler == null) {
permissionsHandler = new AnjoPermissionsHandler(this);
}
return permissionsHandler;
}
/**
*
* @return
*/
public boolean haveUsersChanged() {
if (haveUsersChanged) {
return true;
}
for (User u : users.values()) {
if (u.isChanged()) {
return true;
}
}
return false;
}
/**
*
* @return
*/
public boolean haveGroupsChanged() {
if (haveGroupsChanged) {
return true;
}
for (Group g : groups.values()) {
if (g.isChanged()) {
return true;
}
}
return false;
}
/**
*
*/
public void removeUsersChangedFlag() {
haveUsersChanged = false;
for (User u : users.values()) {
u.flagAsSaved();
}
}
/**
*
*/
public void removeGroupsChangedFlag() {
haveGroupsChanged = false;
for (Group g : groups.values()) {
g.flagAsSaved();
}
}
/**
* @return the usersFile
*/
public File getUsersFile() {
return usersFile;
}
/**
* @return the groupsFile
*/
public File getGroupsFile() {
return groupsFile;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,423 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.dataholder.worlds;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder;
import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
import org.anjocaido.groupmanager.utils.Tasks;
import org.bukkit.entity.Player;
/**
*
* @author gabrielcouto
*/
public class WorldsHolder {
/**
* Map with instances of loaded worlds.
*/
private Map<String, OverloadedWorldHolder> worldsData = new HashMap<String, OverloadedWorldHolder>();
/**
* Map of mirrors: <nonExistingWorldName, existingAndLoadedWorldName>
* The key is the mirror.
* The object is the mirrored.
*
* Mirror shows the same data of mirrored.
*/
private Map<String, String> mirrors = new HashMap<String, String>();
private OverloadedWorldHolder defaultWorld;
private String serverDefaultWorldName;
private GroupManager plugin;
private File worldsFolder;
/**
*
* @param plugin
*/
public WorldsHolder(GroupManager plugin) {
this.plugin = plugin;
verifyFirstRun();
initialLoad();
if (defaultWorld == null) {
throw new IllegalStateException("There is no default group! OMG!");
}
}
private void initialLoad() {
initialWorldLoading();
mirrorSetUp();
}
private void initialWorldLoading(){
//LOAD EVERY WORLD POSSIBLE
loadWorld(serverDefaultWorldName);
defaultWorld = worldsData.get(serverDefaultWorldName);
for (File folder : worldsFolder.listFiles()) {
if (folder.getName().equalsIgnoreCase(serverDefaultWorldName)) {
continue;
}
if (folder.isDirectory()) {
loadWorld(folder.getName());
}
}
}
public void mirrorSetUp(){
mirrors.clear();
Map<String, Object> mirrorsMap = plugin.getConfig().getMirrorsMap();
if (mirrorsMap != null) {
for (String source : mirrorsMap.keySet()) {
if (mirrorsMap.get(source) instanceof ArrayList) {
ArrayList mirrorList = (ArrayList) mirrorsMap.get(source);
for (Object o : mirrorList) {
try {
mirrors.remove(o.toString().toLowerCase());
} catch (Exception e) {
}
mirrors.put(o.toString().toLowerCase(), getWorldData(source).getName());
}
} else if (mirrorsMap.get(source) instanceof Object) {
String aMirror = mirrorsMap.get(source).toString();
mirrors.put(aMirror.toLowerCase(), getWorldData(source).getName());
}
}
}
}
/**
*
*/
public void reloadAll() {
ArrayList<WorldDataHolder> alreadyDone = new ArrayList<WorldDataHolder>();
for (WorldDataHolder w : worldsData.values()) {
if (alreadyDone.contains(w)) {
continue;
}
w.reload();
alreadyDone.add(w);
}
}
/**
*
* @param worldName
*/
public void reloadWorld(String worldName) {
getWorldData(worldName).reload();
}
/**
*
*/
public void saveChanges() {
ArrayList<WorldDataHolder> alreadyDone = new ArrayList<WorldDataHolder>();
for (OverloadedWorldHolder w : worldsData.values()) {
if (alreadyDone.contains(w)) {
continue;
}
Tasks.removeOldFiles(plugin.getBackupFolder());
if (w == null) {
GroupManager.logger.severe("WHAT HAPPENED?");
continue;
}
if (w.haveGroupsChanged()) {
String groupsFolderName = w.getGroupsFile().getParentFile().getName();
File backupGroups = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_g_" + Tasks.getDateString() + ".yml");
try {
Tasks.copy(w.getGroupsFile(), backupGroups);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
WorldDataHolder.writeGroups(w, w.getGroupsFile());
w.removeGroupsChangedFlag();
}
if (w.haveUsersChanged()) {
File backupUsers = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_u_" + Tasks.getDateString() + ".yml");
try {
Tasks.copy(w.getUsersFile(), backupUsers);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
WorldDataHolder.writeUsers(w, w.getUsersFile());
w.removeUsersChangedFlag();
}
alreadyDone.add(w);
}
}
/**
* Returns the dataHolder for the given world.
* If the world is not on the worlds list, returns the default world
* holder.
*
* (WHEN A WORLD IS CONFIGURED TO MIRROR, IT WILL BE ON THE LIST, BUT
* POINTING TO ANOTHER WORLD HOLDER)
*
* Mirrors prevails original data.
*
* @param worldName
* @return
*/
public OverloadedWorldHolder getWorldData(String worldName) {
OverloadedWorldHolder data = worldsData.get(worldName.toLowerCase());
if (mirrors.containsKey(worldName.toLowerCase())) {
String realOne = mirrors.get(worldName.toLowerCase());
data = worldsData.get(realOne.toLowerCase());
}
if (data == null) {
GroupManager.logger.finest("Requested world " + worldName + " not found or badly mirrored. Returning default world...");
data = getDefaultWorld();
}
return data;
}
/**
* Do a matching of playerName, if it s found only one player, do
* getWorldData(player)
* @param playerName
* @return null if matching returned no player, or more than one.
*/
public OverloadedWorldHolder getWorldDataByPlayerName(String playerName) {
List<Player> matchPlayer = plugin.getServer().matchPlayer(playerName);
if (matchPlayer.size() == 1) {
return getWorldData(matchPlayer.get(0));
}
return null;
}
/**
* Retrieves the field p.getWorld().getName() and do
* getWorld(worldName)
* @param p
* @return
*/
public OverloadedWorldHolder getWorldData(Player p) {
return getWorldData(p.getWorld().getName());
}
/**
* It does getWorld(worldName).getPermissionsHandler()
* @param worldName
* @return
*/
public AnjoPermissionsHandler getWorldPermissions(String worldName) {
return getWorldData(worldName).getPermissionsHandler();
}
/**
*It does getWorldData(p).getPermission
* @param p
* @return
*/
public AnjoPermissionsHandler getWorldPermissions(Player p) {
return getWorldData(p).getPermissionsHandler();
}
/**
* Id does getWorldDataByPlayerName(playerName).
* If it doesnt return null, it will return result.getPermissionsHandler()
* @param playerName
* @return null if the player matching gone wrong.
*/
public AnjoPermissionsHandler getWorldPermissionsByPlayerName(String playerName) {
WorldDataHolder dh = getWorldDataByPlayerName(playerName);
if (dh != null) {
return dh.getPermissionsHandler();
}
return null;
}
private void verifyFirstRun() {
worldsFolder = new File(plugin.getDataFolder(), "worlds");
if (!worldsFolder.exists()) {
worldsFolder.mkdirs();
}
Properties server = new Properties();
try {
server.load(new FileInputStream(new File("server.properties")));
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
serverDefaultWorldName = server.getProperty("level-name").toLowerCase();
File defaultWorldFolder = new File(worldsFolder, serverDefaultWorldName);
if (!defaultWorldFolder.exists()) {
defaultWorldFolder.mkdirs();
}
if (defaultWorldFolder.exists()) {
File groupsFile = new File(defaultWorldFolder, "groups.yml");
File usersFile = new File(defaultWorldFolder, "users.yml");
File oldDataFile = new File(plugin.getDataFolder(), "data.yml");
if (!groupsFile.exists()) {
if (oldDataFile.exists()) {
try {
Tasks.copy(oldDataFile, groupsFile);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
} else {
InputStream template = plugin.getResourceAsStream("groups.yml");
try {
Tasks.copy(template, groupsFile);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
}
if (!usersFile.exists()) {
if (oldDataFile.exists()) {
try {
Tasks.copy(oldDataFile, usersFile);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
} else {
InputStream template = plugin.getResourceAsStream("users.yml");
try {
Tasks.copy(template, usersFile);
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
}
}
}
try {
if (oldDataFile.exists()) {
oldDataFile.renameTo(new File(plugin.getDataFolder(), "NOT_USED_ANYMORE_data.yml"));
}
} catch (Exception ex) {
}
}
}
/**
* Copies the specified world data to another world
* @param fromWorld
* @param toWorld
* @return
*/
public boolean cloneWorld(String fromWorld, String toWorld) {
File fromWorldFolder = new File(worldsFolder, fromWorld);
File toWorldFolder = new File(worldsFolder, toWorld);
if (toWorldFolder.exists() || !fromWorldFolder.exists()) {
return false;
}
File fromWorldGroups = new File(fromWorldFolder, "groups.yml");
File fromWorldUsers = new File(fromWorldFolder, "users.yml");
if (!fromWorldGroups.exists() || !fromWorldUsers.exists()) {
return false;
}
File toWorldGroups = new File(toWorldFolder, "groups.yml");
File toWorldUsers = new File(toWorldFolder, "users.yml");
toWorldFolder.mkdirs();
try {
Tasks.copy(fromWorldGroups, toWorldGroups);
Tasks.copy(fromWorldUsers, toWorldUsers);
} catch (IOException ex) {
Logger.getLogger(WorldsHolder.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
}
/**
* Load a world from file.
* If it already been loaded, summon reload method from dataHolder.
* @param worldName
*/
public void loadWorld(String worldName) {
if (worldsData.containsKey(worldName.toLowerCase())) {
worldsData.get(worldName.toLowerCase()).reload();
return;
}
GroupManager.logger.finest("Trying to load world " + worldName + "...");
File thisWorldFolder = new File(worldsFolder, worldName);
if (thisWorldFolder.exists() && thisWorldFolder.isDirectory()) {
File groupsFile = new File(thisWorldFolder, "groups.yml");
File usersFile = new File(thisWorldFolder, "users.yml");
if (!groupsFile.exists()) {
throw new IllegalArgumentException("Groups file for world '" + worldName + "' doesnt exist: " + groupsFile.getPath());
}
if (!usersFile.exists()) {
throw new IllegalArgumentException("Users file for world '" + worldName + "' doesnt exist: " + usersFile.getPath());
}
try {
OverloadedWorldHolder thisWorldData = new OverloadedWorldHolder(WorldDataHolder.load(worldName, groupsFile, usersFile));
if (thisWorldData != null) {
GroupManager.logger.finest("Successful load of world " + worldName + "...");
worldsData.put(worldName.toLowerCase(), thisWorldData);
return;
}
} catch (FileNotFoundException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
return;
} catch (IOException ex) {
GroupManager.logger.log(Level.SEVERE, null, ex);
return;
}
GroupManager.logger.severe("Failed to load world " + worldName + "...");
}
}
/**
* Tells if the such world has been mapped.
*
* It will return true if world is a mirror.
*
* @param worldName
* @return true if world is loaded or mirrored. false if not listed
*/
public boolean isInList(String worldName) {
if (worldsData.containsKey(worldName.toLowerCase()) || mirrors.containsKey(worldName.toLowerCase())) {
return true;
}
return false;
}
/**
* Verify if world has it's own file permissions.
*
* @param worldName
* @return true if it has its own holder. false if not.
*/
public boolean hasOwnData(String worldName) {
if (worldsData.containsKey(worldName.toLowerCase())) {
return true;
}
return false;
}
/**
* @return the defaultWorld
*/
public OverloadedWorldHolder getDefaultWorld() {
return defaultWorld;
}
/**
* Returns all physically loaded worlds.
* @return
*/
public ArrayList<OverloadedWorldHolder> allWorldsDataList() {
ArrayList<OverloadedWorldHolder> list = new ArrayList<OverloadedWorldHolder>();
for (OverloadedWorldHolder data : worldsData.values()) {
if (!list.contains(data)) {
list.add(data);
}
}
return list;
}
}

View File

@@ -0,0 +1,856 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.permissions;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.data.Group;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.data.User;
import org.anjocaido.groupmanager.utils.PermissionCheckResult;
import org.bukkit.entity.Player;
/**
* Everything here maintains the model created by Nijikokun
*
* But implemented to use GroupManager system. Which provides instant changes,
* without file access.
*
* It holds permissions only for one single world.
*
* @author gabrielcouto
*/
public class AnjoPermissionsHandler extends PermissionsReaderInterface {
WorldDataHolder ph = null;
/**
* It needs a WorldDataHolder to work with.
* @param holder
*/
public AnjoPermissionsHandler(WorldDataHolder holder) {
ph = holder;
}
/**
* A short name method, for permission method.
* @param player
* @param permission
* @return
*/
@Override
public boolean has(Player player, String permission) {
return permission(player, permission);
}
/**
* Checks if a player can use that permission node.
* @param player
* @param permission
* @return
*/
@Override
public boolean permission(Player player, String permission) {
return checkUserPermission(ph.getUser(player.getName()), permission);
}
/**
* Returns the name of the group of that player name.
* @param userName
* @return
*/
@Override
public String getGroup(String userName) {
return ph.getUser(userName).getGroup().getName();
}
/**
* Verify if player is in suck group.
* It will check it's groups inheritance.
*
* So if you have a group Admin > Moderator
*
* And verify the player 'MyAdmin', which is Admin, it will return true for both
* Admin or Moderator groups.
*
* Mas if you haave a player 'MyModerator', which is Moderator,
* it will give false if you pass Admin in group parameter.
*
* @param name
* @param group
* @return
*/
@Override
public boolean inGroup(String name, String group) {
if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) {
return true;
}
for (Group subGroup : ph.getUser(name).subGroupListCopy()) {
if (hasGroupInInheritance(subGroup, group)) {
return true;
}
}
return false;
}
/**
* Returns the String prefix for the given group
* @param groupName
* @return empty string if found none.
*/
@Override
public String getGroupPrefix(String groupName) {
Group g = ph.getGroup(groupName);
if (g == null) {
return null;
}
return g.getVariables().getVarString("prefix");
}
/**
* Return the suffix for the given group name
* @param groupName
* @return
*/
@Override
public String getGroupSuffix(String groupName) {
Group g = ph.getGroup(groupName);
if (g == null) {
return null;
}
return g.getVariables().getVarString("suffix");
}
/**
*
* @param groupName
* @return
*/
@Override
public boolean canGroupBuild(String groupName) {
Group g = ph.getGroup(groupName);
if (g == null) {
return false;
}
return g.getVariables().getVarBoolean("build");
}
/**
* It returns a string variable value, set in the INFO node of the group.
* It will harvest inheritance for value.
* @param groupName
* @param variable
* @return null if no group with that variable is found.
*/
@Override
public String getGroupPermissionString(String groupName, String variable) {
Group start = ph.getGroup(groupName);
if (start == null) {
return null;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return null;
}
return result.getVariables().getVarString(variable);
}
/**
* It returns a Integer variable value
* It will harvest inheritance for value.
* @param groupName
* @param variable
* @return -1 if none found or not parseable.
*/
@Override
public int getGroupPermissionInteger(String groupName, String variable) {
Group start = ph.getGroup(groupName);
if (start == null) {
return -1;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return -1;
}
return result.getVariables().getVarInteger(variable);
}
/**
* Returns a boolean for given variable in INFO node.
* It will harvest inheritance for value.
* @param group
* @param variable
* @return false if not found/not parseable.
*/
@Override
public boolean getGroupPermissionBoolean(String group, String variable) {
Group start = ph.getGroup(group);
if (start == null) {
return false;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return false;
}
return result.getVariables().getVarBoolean(variable);
}
/**
* Returns a double value for the given variable name in INFO node.
* It will harvest inheritance for value.
* @param group
* @param variable
* @return -1 if not found / not parseable.
*/
@Override
public double getGroupPermissionDouble(String group, String variable) {
Group start = ph.getGroup(group);
if (start == null) {
return -1;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return -1;
}
return result.getVariables().getVarDouble(variable);
}
/**
* Returns the variable value of the user, in INFO node.
* @param user
* @param variable
* @return
*/
@Override
public String getUserPermissionString(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return "";
}
return auser.getVariables().getVarString(variable);
}
/**
* Returns the variable value of the user, in INFO node.
* @param user
* @param variable
* @return
*/
@Override
public int getUserPermissionInteger(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return -1;
}
return auser.getVariables().getVarInteger(variable);
}
/**
* Returns the variable value of the user, in INFO node.
* @param user
* @param variable
* @return
*/
@Override
public boolean getUserPermissionBoolean(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return false;
}
return auser.getVariables().getVarBoolean(variable);
}
/**
* Returns the variable value of the user, in INFO node.
* @param user
* @param variable
* @return
*/
@Override
public double getUserPermissionDouble(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return -1;
}
return auser.getVariables().getVarDouble(variable);
}
/**
* Returns the variable value of the user, in INFO node.
* If not found, it will search for his Group variables.
* It will harvest the inheritance.
* @param user
* @param variable
* @return empty string if not found
*/
@Override
public String getPermissionString(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return "";
}
if (auser.getVariables().hasVar(variable)) {
return auser.getVariables().getVarString(variable);
}
Group start = auser.getGroup();
if (start == null) {
return "";
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return "";
}
return result.getVariables().getVarString(variable);
//return getUserPermissionString(user, variable);
}
/**
* Returns the variable value of the user, in INFO node.
* If not found, it will search for his Group variables.
* It will harvest the inheritance.
* @param user
* @param variable
* @return -1 if not found
*/
@Override
public int getPermissionInteger(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return -1;
}
if (auser.getVariables().hasVar(variable)) {
return auser.getVariables().getVarInteger(variable);
}
Group start = auser.getGroup();
if (start == null) {
return -1;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return -1;
}
return result.getVariables().getVarInteger(variable);
//return getUserPermissionInteger(string, string1);
}
/**
* Returns the variable value of the user, in INFO node.
* If not found, it will search for his Group variables.
* It will harvest the inheritance.
* @param user
* @param variable
* @return false if not found or not parseable to true.
*/
@Override
public boolean getPermissionBoolean(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return false;
}
if (auser.getVariables().hasVar(variable)) {
return auser.getVariables().getVarBoolean(variable);
}
Group start = auser.getGroup();
if (start == null) {
return false;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return false;
}
return result.getVariables().getVarBoolean(variable);
//return getUserPermissionBoolean(user, string1);
}
/**
* Returns the variable value of the user, in INFO node.
* If not found, it will search for his Group variables.
* It will harvest the inheritance.
* @param user
* @param variable
* @return -1 if not found.
*/
@Override
public double getPermissionDouble(String user, String variable) {
User auser = ph.getUser(user);
if (auser == null) {
return -1.0D;
}
if (auser.getVariables().hasVar(variable)) {
return auser.getVariables().getVarDouble(variable);
}
Group start = auser.getGroup();
if (start == null) {
return -1.0D;
}
Group result = nextGroupWithVariable(start, variable);
if (result == null) {
return -1.0D;
}
return result.getVariables().getVarDouble(variable);
//return getUserPermissionDouble(string, string1);
}
/**
* Does not include User's group permission
* @param user
* @param permission
* @return
*/
public PermissionCheckResult checkUserOnlyPermission(User user, String permission) {
user.sortPermissions();
PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = permission;
result.owner = user;
for (String access : user.getPermissionList()) {
if (comparePermissionString(access, permission)) {
result.accessLevel = access;
if (access.startsWith("-")) {
result.resultType = PermissionCheckResult.Type.NEGATION;
} else if (access.startsWith("+")) {
result.resultType = PermissionCheckResult.Type.EXCEPTION;
} else {
result.resultType = PermissionCheckResult.Type.FOUND;
}
return result;
}
}
result.resultType = PermissionCheckResult.Type.NOTFOUND;
return result;
}
/**
* Returns the node responsible for that permission.
* Does not include User's group permission.
* @param group
* @param permission
* @return the node if permission is found. if not found, return null
*/
public PermissionCheckResult checkGroupOnlyPermission(Group group, String permission) {
group.sortPermissions();
PermissionCheckResult result = new PermissionCheckResult();
result.owner = group;
result.askedPermission = permission;
for (String access : group.getPermissionList()) {
if (comparePermissionString(access, permission)) {
result.accessLevel = access;
if (access.startsWith("-")) {
result.resultType = PermissionCheckResult.Type.NEGATION;
} else if (access.startsWith("+")) {
result.resultType = PermissionCheckResult.Type.EXCEPTION;
} else {
result.resultType = PermissionCheckResult.Type.FOUND;
}
return result;
}
}
result.resultType = PermissionCheckResult.Type.NOTFOUND;
return result;
}
/**
* Check permissions, including it's group and inheritance.
* @param user
* @param permission
* @return true if permission was found. false if not, or was negated.
*/
public boolean checkUserPermission(User user, String permission) {
PermissionCheckResult result = checkFullUserPermission(user, permission);
if (result.resultType.equals(PermissionCheckResult.Type.EXCEPTION)
|| result.resultType.equals(PermissionCheckResult.Type.FOUND)) {
return true;
}
return false;
}
/**
* Do what checkUserPermission did before. But now returning a PermissionCheckResult.
* @param user
* @param targetPermission
* @return
*/
public PermissionCheckResult checkFullUserPermission(User user, String targetPermission) {
PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND;
if (user == null || targetPermission == null) {
return result;
}
PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission);
if (!resultUser.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) {
return resultUser;
}
//IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT FOUND
PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission);
if (!resultGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) {
return resultGroup;
}
//SUBGROUPS CHECK
for (Group subGroup : user.subGroupListCopy()) {
PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission);
if (!resultSubGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) {
return resultSubGroup;
}
}
//THEN IT RETURNS A NOT FOUND
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
* variable name.
*
* It does Breadth-first search
*
* @param start the starting group to look for
* @param targetVariable the variable name
* @return The group if found. Null if not.
*/
public Group nextGroupWithVariable(Group start, String targetVariable) {
if (start == null || targetVariable == null) {
return null;
}
LinkedList<Group> stack = new LinkedList<Group>();
ArrayList<Group> alreadyVisited = new ArrayList<Group>();
stack.push(start);
alreadyVisited.add(start);
while (!stack.isEmpty()) {
Group now = stack.pop();
if (now.getVariables().hasVar(targetVariable)) {
return now;
}
for (String sonName : now.getInherits()) {
Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son)) {
stack.push(son);
alreadyVisited.add(son);
}
}
}
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.
*
* It does Breadth-first search
*
* @param start The group to start the search.
* @param askedGroup Name of the group you're looking for
* @return true if it inherits the group.
*/
public boolean hasGroupInInheritance(Group start, String askedGroup) {
if (start == null || askedGroup == null) {
return false;
}
LinkedList<Group> stack = new LinkedList<Group>();
ArrayList<Group> alreadyVisited = new ArrayList<Group>();
stack.push(start);
alreadyVisited.add(start);
while (!stack.isEmpty()) {
Group now = stack.pop();
if (now.getName().equalsIgnoreCase(askedGroup)) {
return true;
}
for (String sonName : now.getInherits()) {
Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son)) {
stack.push(son);
alreadyVisited.add(son);
}
}
}
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(result.resultType.EXCEPTION)
|| result.resultType.equals(result.resultType.FOUND)) {
return true;
}
return false;
}
/**
* Returns the result of permission check. Including inheritance.
* If found anything, the PermissionCheckResult that retuns will
* include the Group name, and the result type.
* Result types will be EXCEPTION, NEGATION, FOUND.
*
* If returned type NOTFOUND, the owner will be null,
* and ownerType too.
*
* It does Breadth-first search
*
* @param start
* @param targetPermission
* @return
*/
public PermissionCheckResult checkGroupPermissionWithInheritance(Group start, String targetPermission) {
if (start == null || targetPermission == null) {
return null;
}
LinkedList<Group> stack = new LinkedList<Group>();
List<Group> alreadyVisited = new ArrayList<Group>();
stack.push(start);
alreadyVisited.add(start);
while (!stack.isEmpty()) {
Group now = stack.pop();
PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission);
if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) {
return resultNow;
}
for (String sonName : now.getInherits()) {
Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son)) {
stack.push(son);
alreadyVisited.add(son);
}
}
}
PermissionCheckResult result = new PermissionCheckResult();
result.askedPermission = targetPermission;
result.resultType = PermissionCheckResult.Type.NOTFOUND;
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(result.resultType.EXCEPTION)
|| result.resultType.equals(result.resultType.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
* starting group.
*
* It does Breadth-first search. So closer groups will appear first in list.
*
* @param start
* @return the group that passed on test. null if no group passed.
*/
public ArrayList<String> listAllGroupsInherited(Group start) {
if (start == null) {
return null;
}
LinkedList<Group> stack = new LinkedList<Group>();
ArrayList<String> alreadyVisited = new ArrayList<String>();
stack.push(start);
alreadyVisited.add(start.getName());
while (!stack.isEmpty()) {
Group now = stack.pop();
for (String sonName : now.getInherits()) {
Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son.getName())) {
stack.push(son);
alreadyVisited.add(son.getName());
}
}
}
return alreadyVisited;
}
/**
* Compare a user permission like 'myplugin.*' against a full plugin
* permission name, like 'myplugin.dosomething'.
* As the example above, will return true.
*
* Please sort permissions before sending them here. So negative tokens
* get priority.
*
* You must test if it start with negative outside this method. It will
* only tell if the nodes are matching or not.
*
* Every '-' or '+' in the beginning is ignored. It will match only
* node names.
*
* @param userAcessLevel
* @param fullPermissionName
* @return true if found a matching token. false if not.
*/
public boolean comparePermissionString(String userAcessLevel, String fullPermissionName) {
if (userAcessLevel == null || fullPermissionName == null) {
return false;
}
GroupManager.logger.finest("COMPARING " + userAcessLevel + " WITH " + fullPermissionName);
if (userAcessLevel.startsWith("+")) {
userAcessLevel = userAcessLevel.substring(1);
} else if (userAcessLevel.startsWith("-")) {
userAcessLevel = userAcessLevel.substring(1);
}
if (fullPermissionName.startsWith("+")) {
fullPermissionName = fullPermissionName.substring(1);
} else if (fullPermissionName.startsWith("-")) {
fullPermissionName = fullPermissionName.substring(1);
}
StringTokenizer levelATokenizer = new StringTokenizer(userAcessLevel, ".");
StringTokenizer levelBTokenizer = new StringTokenizer(fullPermissionName, ".");
while (levelATokenizer.hasMoreTokens() && levelBTokenizer.hasMoreTokens()) {
String levelA = levelATokenizer.nextToken();
String levelB = levelBTokenizer.nextToken();
GroupManager.logger.finest("ROUND " + levelA + " AGAINST " + levelB);
if (levelA.contains("*")) {
GroupManager.logger.finest("WIN");
return true;
}
if (levelA.equalsIgnoreCase(levelB)) {
if (!levelATokenizer.hasMoreTokens() && !levelBTokenizer.hasMoreTokens()) {
GroupManager.logger.finest("WIN");
return true;
}
GroupManager.logger.finest("NEXT");
continue;
} else {
GroupManager.logger.finest("FAIL");
return false;
}
}
GroupManager.logger.finest("FAIL");
return false;
}
/**
* Returns a list of all groups.
*
* Including subgroups.
* @param userName
* @return
*/
public String[] getGroups(String userName) {
ArrayList<String> allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup());
for(Group subg: ph.getUser(userName).subGroupListCopy()){
allGroups.addAll(listAllGroupsInherited(subg));
}
String[] arr = new String[allGroups.size()];
return allGroups.toArray(arr);
}
/**
* A Breadth-first search thru inheritance model.
*
* Just a model to copy and paste.
* This will guarantee the closer groups will be checked first.
* @param start
* @param targerPermission
* @return
*/
private Group breadthFirstSearch(Group start, String targerPermission) {
if (start == null || targerPermission == null) {
return null;
}
LinkedList<Group> stack = new LinkedList<Group>();
ArrayList<Group> alreadyVisited = new ArrayList<Group>();
stack.push(start);
alreadyVisited.add(start);
while (!stack.isEmpty()) {
Group now = stack.pop();
PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targerPermission);
if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION)
|| resultNow.resultType.equals(PermissionCheckResult.Type.FOUND)) {
return now;
}
if (resultNow.resultType.equals(PermissionCheckResult.Type.NEGATION)) {
return null;
}
for (String sonName : now.getInherits()) {
Group son = ph.getGroup(sonName);
if (son != null && !alreadyVisited.contains(son)) {
stack.push(son);
alreadyVisited.add(son);
}
}
}
return null;
}
}

View File

@@ -0,0 +1,163 @@
package org.anjocaido.groupmanager.permissions;
import org.bukkit.entity.Player;
/**
* Made by Nijikokun. Changed by Gabriel Couto
*
* This class is intended to *read* permissions from a single world.
*
* @author Nijikokun
* @author Gabriel Couto
*/
public abstract class PermissionsReaderInterface {
/**
*
* @param player
* @param string
* @return
*/
public abstract boolean has(Player player, String string);
/**
*
* @param player
* @param string
* @return
*/
public abstract boolean permission(Player player, String string);
/**
*
* @param string
* @return
*/
public abstract String getGroup(String string);
/**
*
* @param string
* @param string1
* @return
*/
public abstract boolean inGroup(String string, String string1);
/**
*
* @param string
* @return
*/
public abstract String getGroupPrefix(String string);
/**
*
* @param string
* @return
*/
public abstract String getGroupSuffix(String string);
/**
*
* @param string
* @return
*/
public abstract boolean canGroupBuild(String string);
/**
*
* @param string
* @param string1
* @return
*/
public abstract String getGroupPermissionString(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract int getGroupPermissionInteger(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract boolean getGroupPermissionBoolean(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract double getGroupPermissionDouble(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract String getUserPermissionString(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract int getUserPermissionInteger(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract boolean getUserPermissionBoolean(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract double getUserPermissionDouble(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract String getPermissionString(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract int getPermissionInteger(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract boolean getPermissionBoolean(String string, String string1);
/**
*
* @param string
* @param string1
* @return
*/
public abstract double getPermissionDouble(String string, String string1);
}

View File

@@ -0,0 +1,26 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.utils;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
*
* @author gabrielcouto
*/
public class GMLoggerHandler extends ConsoleHandler {
@Override
public void publish(LogRecord record) {
String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage();
if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) {
System.err.println(message);
} else {
System.out.println(message);
}
}
}

View File

@@ -0,0 +1,51 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.utils;
/**
* Just a list of commands for this plugin
* @author gabrielcouto
*/
public enum GroupManagerPermissions {
manuadd,
manudel,
manuaddsub,
manudelsub,
mangadd,
mangdel,
manuaddp,
manudelp,
manulistp,
manucheckp,
mangaddp,
mangdelp,
manglistp,
mangcheckp,
mangaddi,
mangdeli,
manuaddv,
manudelv,
manulistv,
manucheckv,
mangaddv,
mangdelv,
manglistv,
mangcheckv,
manwhois,
tempadd,
tempdel,
templist,
tempdelall,
mansave,
manload,
listgroups,
manpromote,
mandemote,
mantogglevalidate,
mantogglesave,
manworld,
manselect,
manclear
}

View File

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

View File

@@ -0,0 +1,50 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.utils;
import java.util.Comparator;
/**
*
* @author gabrielcouto
*/
public class StringPermissionComparator implements Comparator<String> {
@Override
public int compare(String permA, String permB) {
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(){
if(instance==null){
instance = new StringPermissionComparator();
}
return instance;
}
}

View File

@@ -0,0 +1,111 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anjocaido.groupmanager.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import org.anjocaido.groupmanager.data.Group;
/**
*
* @author gabrielcouto
*/
public abstract class Tasks {
public static void copy(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
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);
}
public static void removeOldFiles(File folder) {
if (folder.isDirectory()) {
long oldTime = System.currentTimeMillis() - 86400000L;
for (File olds : folder.listFiles()) {
if (olds.isFile()) {
if (olds.lastModified() < oldTime) {
try {
olds.delete();
} catch (Exception e) {
}
}
}
}
}
}
public static String getDateString() {
GregorianCalendar now = new GregorianCalendar();
String date = "";
date += now.get(GregorianCalendar.DAY_OF_MONTH);
date += "-";
date += now.get(GregorianCalendar.HOUR);
date += "-";
date += now.get(GregorianCalendar.MINUTE);
return date;
}
public static String getStringListInString(List<String> list){
if(list==null){
return "";
}
String result="";
for(int i=0;i<list.size();i++){
result+=list.get(i);
if(i<list.size()-1){
result+=", ";
}
}
return result;
}
public static String getStringArrayInString(String[] list){
if(list==null){
return "";
}
String result="";
for(int i=0;i<list.length;i++){
result+=list[i];
if(i<((list.length)-1)){
result+=", ";
}
}
return result;
}
public static String getGroupListInString(List<Group> list){
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;
}
}

View File

@@ -0,0 +1,165 @@
name: GroupManager
version: 1.0(alpha-5)
main: org.anjocaido.groupmanager.GroupManager
website: http://www.anjocaido.info/
description: Provides on-the-fly system for Permission system created by Nijikokun. But all in memory, and with flat-file saving schedule.
authors:
- AnjoCaido
- Gabriel Couto
commands:
manuadd:
description: Move a player to desired group.(Adds to the file if not exists)
usage: /<command> <player> <group>
permission: groupmanager.manuadd
manudel:
description: Remove any user specific configuration. Make him default group.
usage: /<command> <player>
permission: groupmanager.manudel
manuaddsub:
description: Add a group to a player's subgroup list.
usage: /<command> <player> <group>
permission: groupmanager.manuaddsub
manudelsub:
description: Remove a group to a player's subgroup list.
usage: /<command> <player> <group>
permission: groupmanager.manudelsub
mangadd:
description: Add group to the system.
usage: /<command> <group>
permission: groupmanager.mangadd
mangdel:
description: Removes group from the system(all it's users become default)
usage: /<command> <group>
permission: groupmanager.mangdel
manuaddp:
description: Add permission diretly to the player.
usage: /<command> <player> <permission>
permission: groupmanager.manuaddp
manudelp:
description: Removes permission diretly from the player.
usage: /<command> <player> <permission>
permission: groupmanager.manudelp
manulistp:
description: List all permissions from a player.
usage: /<command> <player>
permission: groupmanager.manulistp
manucheckp:
description: Verify if user has a permission, and where it comes from.
usage: /<command> <player> <permission>
permission: groupmanager.manucheckp
mangaddp:
description: Add permission to a group.
usage: /<command> <group> <permission>
permission: groupmanager.mangaddp
mangdelp:
description: Removes permission from a group.
usage: /<command> <group> <permission>
permission: groupmanager.mangdelp
manglistp:
description: Lists all permissions from a group.
usage: /<command> <group>
permission: groupmanager.manglistp
mangcheckp:
description: Check if group has a permission, and where it comes from.
usage: /<command> <group> <permission>
permission: groupmanager.mangcheckp
mangaddi:
description: Add a group to another group inheritance list.
usage: /<command> <group1> <group2>
permission: groupmanager.mangaddi
mangdeli:
description: Remove a group from another group inheritance list.
usage: /<command> <group1> <group2>
permission: groupmanager.mangdeli
manuaddv:
description: Add, or replaces, a variable to a user (like prefix or suffix).
usage: /<command> <user> <variable> <value>
permission: groupmanager.manuaddv
manudelv:
description: Remove a variable from a user.
usage: /<command> <user> <variable>
permission: groupmanager.manudelv
manulistv:
description: List variables a user has (like prefix or suffix).
usage: /<command> <user>
permission: groupmanager.manulistv
manucheckv:
description: Verify a value of a variable of user, and where it comes from.
usage: /<command> <user> <variable>
permission: groupmanager.manucheckv
mangaddv:
description: Add, or replaces, a variable to a group (like prefix or suffix).
usage: /<command> <group> <variable> <value>
permission: groupmanager.mangaddv
mangdelv:
description: Remove a variable from a group.
usage: /<command> <group> <variable>
permission: groupmanager.mangdelv
manglistv:
description: List variables a group has (like prefix or suffix).
usage: /<command> <group>
permission: groupmanager.manglistv
mangcheckv:
description: Verify a value of a variable of group, and where it comes from.
usage: /<command> <group> <variable>
permission: groupmanager.mangckeckv
manwhois:
description: Tell the group that user belongs.
usage: /<command> <player>
permission: groupmanager.manwhois
tempadd:
description: Creates a temporary permission copy for that user.
usage: /<command> <player>
permission: groupmanager.tempadd
tempdel:
description: Remove the temporary permission copy for player.
usage: /<command> <player>
permission: groupmanager.tempdel
templist:
description: List players in overload-permissions mode made by /tempadd.
usage: /<command>
permission: groupmanager.templist
tempdelall:
description: Remove all overrides made by command /tempadd.
usage: /<command>
permission: groupmanager.tempdelall
mansave:
description: Save all permissions on file.
usage: /<command>
permission: groupmanager.mansave
manload:
description: Reload current world and config.yml. Or load given world.
usage: /<command> [world]
permission: groupmanager.manload
listgroups:
description: List the groups available.
usage: /<command>
permission: groupmanager.listgroups
manpromote:
description: Promote a player in the same heritage line to a higher rank.
usage: /<command> <player> <group>
permission: groupmanager.manpromote
mandemote:
description: Demote a player in the same heritage line to a lower rank.
usage: /<command> <player> <group>
permission: groupmanager.mandemote
mantogglevalidate:
description: Toggle on/off the validating if player is online.
usage: /<command>
permission: groupmanager.mantogglevalidate
mantogglesave:
description: Toggle on/ff the autosave.
usage: /<command>
permission: groupmanager.mantogglesave
manworld:
description: Prints the selected world name
usage: /<command>
permission: groupmanager.manworld
manselect:
description: Select a world to work with next commands.
usage: /<command> <world>
permission: groupmanager.manselect
manclear:
description: Clear world selection. Next commands will work on your world.
usage: /<command>
permission: groupmanager.manclear

View File

@@ -0,0 +1,59 @@
users:
aMiner:
subgroups:
- Miner
permissions: []
group: BlueFaction
info:
prefix: '&d'
suffix: Miner
gmcouto:
subgroups: []
permissions: []
group: SemiAdmin
tempRailer:
subgroups:
- Miner
- Railer
permissions: []
group: BlueFaction
info:
prefix: '&d'
suffix: Miner
anjocaido:
subgroups: []
permissions: []
group: Admin
info:
prefix: '&c'
suffix: King
aFarmer:
subgroups:
- Farmer
permissions: []
group: RedFaction
info:
prefix: '&d'
suffix: Farmer
zenexer:
subgroups: []
permissions:
- essentials.god
group: Moderator
Teste:
subgroups:
- Miner
- Railer
- SuperCart
- Fighter
- FlyingMan
permissions: []
group: BlueFaction
aHealer:
subgroups:
- Healer
permissions: []
group: RedFaction
info:
prefix: '&d'
suffix: Healer