Move everything out of folder, I guess

This commit is contained in:
xaw3ep 2021-03-28 18:53:09 +07:00
parent 81a8f6e624
commit 02b343eaf1
44 changed files with 4627 additions and 4631 deletions

View File

@ -1,8 +0,0 @@
/.settings
/.classpath
/.project
/jar_desc.jardesc
/target
/bin
/.gitignore
/local-maven/

File diff suppressed because it is too large Load Diff

4
README.md Normal file
View File

@ -0,0 +1,4 @@
CompatNoCheatPlus
CompatNoCheatPlus (cncp) provides compatibility between the anti cheat plugin NoCheatPlus and other plugins that add game mechanics different to the vanilla game behavior, such as mcMMO or plugins that add npcs such as Citizens and protocol hack like Geyser for cross-platform to play with.

View File

@ -1,72 +1,72 @@
CompatNoCheatPlus lists file
-------------------------------------------------------
Compatibility hooks for NoCheatPlus!
LICENSE
-------------------------
LICENSE.txt (Same as NoCheatPlus).
STACK
---------
?(add) more intricate load order stuff ? [best would be to force managelisteners with ncp]
***
!(add) reload command
? another sequence number (for standard events)
*** ADD MORE GENERIC HOOKS
!add check type and permission hooks, also for worldguard regions.
Citizens2 / Player class: make configurable (hidden) Or do internally: List of checks to use , exclude moving if possible.
Generic abstract class for the mcMMO style cancelling of next x events + ticks alive etc
add stats hook ?
add a good mechanism for adding external configurable hooks (read automatically from the cncp config).
!(add) Use some exemption mechanism for npcs (generic player class hook + citizens).
!consider remove: clearing the VL ? => probably not, needs redesign to also monitor block break. + only clear the necessary bits (not frequency)
! try: insta break: keep exemption (unless cancelled) for next block break event (!). -> maybe ncp
? HookInstaBreak : add static method to sset check types to exempt from for next break ?
cncp: check at least for logs / leaves for skill specific block types
hookiinstabreak: let hooks fail completely if listeners are failing to register ?
*** CLEANUP THIS, BETTER METHODS, INTEGRATE SOME INTO NCP MAYBE
* Auto detection of unknown events + log on disable + info command.
? analysis tools like event-Mirror ?
* More generic hooks, clean methods!
! Strip down mcMMO hook to add a new one / integrate into instabreak
! Clean up hooks, use TickTask and "next" to confine fuzzy unexemption to a minimum.
--------------------------
support for instant spells ? [internalName or name ? <- guess: name]
? register listeners with NCP directly? also use annotations ?
! Smarter way to enable / disable PlayerClassHoook (disable by default for now).
! if SpoutPlugin is present: add blocks to ignorepassable automatically / adjust flags ? [generic block setup]
? add info command: show all hooks and so on.
add class-name inspection methods (!).
set-speed: per world options ? [per world config concept]
set-speed: add option to set speed to default speed on player quit/kick
CompatNoCheatPlus lists file
-------------------------------------------------------
Compatibility hooks for NoCheatPlus!
LICENSE
-------------------------
LICENSE.txt (Same as NoCheatPlus).
STACK
---------
?(add) more intricate load order stuff ? [best would be to force managelisteners with ncp]
***
!(add) reload command
? another sequence number (for standard events)
*** ADD MORE GENERIC HOOKS
!add check type and permission hooks, also for worldguard regions.
Citizens2 / Player class: make configurable (hidden) Or do internally: List of checks to use , exclude moving if possible.
Generic abstract class for the mcMMO style cancelling of next x events + ticks alive etc
add stats hook ?
add a good mechanism for adding external configurable hooks (read automatically from the cncp config).
!(add) Use some exemption mechanism for npcs (generic player class hook + citizens).
!consider remove: clearing the VL ? => probably not, needs redesign to also monitor block break. + only clear the necessary bits (not frequency)
! try: insta break: keep exemption (unless cancelled) for next block break event (!). -> maybe ncp
? HookInstaBreak : add static method to sset check types to exempt from for next break ?
cncp: check at least for logs / leaves for skill specific block types
hookiinstabreak: let hooks fail completely if listeners are failing to register ?
*** CLEANUP THIS, BETTER METHODS, INTEGRATE SOME INTO NCP MAYBE
* Auto detection of unknown events + log on disable + info command.
? analysis tools like event-Mirror ?
* More generic hooks, clean methods!
! Strip down mcMMO hook to add a new one / integrate into instabreak
! Clean up hooks, use TickTask and "next" to confine fuzzy unexemption to a minimum.
--------------------------
support for instant spells ? [internalName or name ? <- guess: name]
? register listeners with NCP directly? also use annotations ?
! Smarter way to enable / disable PlayerClassHoook (disable by default for now).
! if SpoutPlugin is present: add blocks to ignorepassable automatically / adjust flags ? [generic block setup]
? add info command: show all hooks and so on.
add class-name inspection methods (!).
set-speed: per world options ? [per world config concept]
set-speed: add option to set speed to default speed on player quit/kick

View File

@ -1,19 +1,19 @@
name: CompatNoCheatPlus
main: me.asofold.bpl.cncp.CompatNoCheatPlus
version: ${project.version}-${buildDescription}
dev-url: http://dev.bukkit.org/server-mods/compatnocheatplus-cncp/
loadbefore:
- NoCheatPlus
softdepend:
- mcMMO
- Citizens
- MagicSpells
commands:
compatnocheatplus:
description: 'Show general version information of cncp and dependencies.'
usage: '/<command>'
permission: 'cncp.cmd.info'
aliases:
- cncp
name: CompatNoCheatPlus
main: me.asofold.bpl.cncp.CompatNoCheatPlus
version: ${project.version}-${buildDescription}
dev-url: http://dev.bukkit.org/server-mods/compatnocheatplus-cncp/
loadbefore:
- NoCheatPlus
softdepend:
- mcMMO
- Citizens
- MagicSpells
commands:
compatnocheatplus:
description: 'Show general version information of cncp and dependencies.'
usage: '/<command>'
permission: 'cncp.cmd.info'
aliases:
- cncp

View File

@ -1,186 +1,186 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CompatNoCheatPlus</groupId>
<artifactId>CompatNoCheatPlus</artifactId>
<version>6.6.7-SNAPSHOT</version>
<name>CompatNoCheatPlus</name>
<!-- Source code -->
<scm>
<developerConnection>scm:git:git@github.com:asofold/${project.name}.git</developerConnection>
<connection>scm:git:git://github.com/asofold/${project.name}.git</connection>
<url>https://github.com/asofold/${project.name}</url>
</scm>
<!-- Repositories -->
<repositories>
<repository>
<id>repo-public</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
</repository>
<repository>
<id>opencollab-snapshot-repo</id>
<url>https://repo.opencollab.dev/maven-snapshots/</url>
</repository>
<repository>
<id>repo-nms</id>
<url>https://repo.codemc.org/repository/nms/</url>
</repository>
</repositories>
<!-- Dependencies -->
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId>
<version>2.1.158</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.citizensnpcs</groupId>
<artifactId>citizensapi</artifactId>
<version>2.0.26-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.benzoft.gravitytubes</groupId>
<artifactId>gravitytubes</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/libs/GravityTubes.jar</systemPath>
</dependency>
<dependency>
<groupId>com.Zrips.CMI</groupId>
<artifactId>CMI</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/libs/CMIAPI7.6.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>fr.neatmonster</groupId>
<artifactId>nocheatplus</artifactId>
<version>3.17-SNAPSHOT-Updated</version>
<scope>system</scope>
<systemPath>${basedir}/libs/NoCheatPlus.jar</systemPath>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.2.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>floodgate-bukkit</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>floodgate-bungee</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.steveice10</groupId>
<artifactId>mcprotocollib</artifactId>
<version>1.16.4-2-20210115.210558-6</version>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.16-R0.5-20210213.224112-6</version>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-event</artifactId>
<version>1.16-R0.5-20210213.224052-6</version>
</dependency>
</dependencies>
<!-- Build Description Profiles -->
<profiles>
<profile>
<id>timestamp</id>
<activation>
<property>
<name>!env.BUILD_NUMBER</name>
</property>
</activation>
<properties>
<buildDescription>${maven.build.timestamp}</buildDescription>
</properties>
</profile>
<profile>
<id>dynamic_build_number</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<properties>
<buildDescription>b${env.BUILD_NUMBER}</buildDescription>
</properties>
</profile>
</profiles>
<!-- Building -->
<build>
<defaultGoal>clean package</defaultGoal>
<sourceDirectory>${basedir}/src</sourceDirectory>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}</directory>
<includes>
<include>plugin.yml</include>
<include>LICENSE.txt</include>
<include>bungee.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<finalName>cncp</finalName>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<pomPropertiesFile>false</pomPropertiesFile>
<manifest>
<addDefaultSpecificationEntries>false</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<!-- Properties -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>yyyy_MM_dd-HH_mm</maven.build.timestamp.format>
</properties>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CompatNoCheatPlus</groupId>
<artifactId>CompatNoCheatPlus</artifactId>
<version>6.6.7-SNAPSHOT</version>
<name>CompatNoCheatPlus</name>
<!-- Source code -->
<scm>
<developerConnection>scm:git:git@github.com:asofold/${project.name}.git</developerConnection>
<connection>scm:git:git://github.com/asofold/${project.name}.git</connection>
<url>https://github.com/asofold/${project.name}</url>
</scm>
<!-- Repositories -->
<repositories>
<repository>
<id>repo-public</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
</repository>
<repository>
<id>opencollab-snapshot-repo</id>
<url>https://repo.opencollab.dev/maven-snapshots/</url>
</repository>
<repository>
<id>repo-nms</id>
<url>https://repo.codemc.org/repository/nms/</url>
</repository>
</repositories>
<!-- Dependencies -->
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.8.8-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId>
<version>2.1.158</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.citizensnpcs</groupId>
<artifactId>citizensapi</artifactId>
<version>2.0.26-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.benzoft.gravitytubes</groupId>
<artifactId>gravitytubes</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/libs/GravityTubes.jar</systemPath>
</dependency>
<dependency>
<groupId>com.Zrips.CMI</groupId>
<artifactId>CMI</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/libs/CMIAPI7.6.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>fr.neatmonster</groupId>
<artifactId>nocheatplus</artifactId>
<version>3.17-SNAPSHOT-Updated</version>
<scope>system</scope>
<systemPath>${basedir}/libs/NoCheatPlus.jar</systemPath>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>connector</artifactId>
<version>1.2.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>floodgate-bukkit</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>floodgate-bungee</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.steveice10</groupId>
<artifactId>mcprotocollib</artifactId>
<version>1.16.4-2-20210115.210558-6</version>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.16-R0.5-20210213.224112-6</version>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-event</artifactId>
<version>1.16-R0.5-20210213.224052-6</version>
</dependency>
</dependencies>
<!-- Build Description Profiles -->
<profiles>
<profile>
<id>timestamp</id>
<activation>
<property>
<name>!env.BUILD_NUMBER</name>
</property>
</activation>
<properties>
<buildDescription>${maven.build.timestamp}</buildDescription>
</properties>
</profile>
<profile>
<id>dynamic_build_number</id>
<activation>
<property>
<name>env.BUILD_NUMBER</name>
</property>
</activation>
<properties>
<buildDescription>b${env.BUILD_NUMBER}</buildDescription>
</properties>
</profile>
</profiles>
<!-- Building -->
<build>
<defaultGoal>clean package</defaultGoal>
<sourceDirectory>${basedir}/src</sourceDirectory>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>${basedir}</directory>
<includes>
<include>plugin.yml</include>
<include>LICENSE.txt</include>
<include>bungee.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<finalName>cncp</finalName>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<pomPropertiesFile>false</pomPropertiesFile>
<manifest>
<addDefaultSpecificationEntries>false</addDefaultSpecificationEntries>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<!-- Properties -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>yyyy_MM_dd-HH_mm</maven.build.timestamp.format>
</properties>
</project>

View File

@ -1,91 +1,91 @@
package me.asofold.bpl.cncp.config;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;
import org.bukkit.Bukkit;
import fr.neatmonster.nocheatplus.checks.CheckType;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.config.compatlayer.NewConfig;
public class Settings {
public static final int configVersion = 2;
public Set<String> forceEnableLater = new LinkedHashSet<String>();
public Set<String> loadPlugins = new LinkedHashSet<String>();
public Set<CheckType> extemptChecks = new LinkedHashSet<CheckType>();
public static Set<String> preventAddHooks = new HashSet<String>();
public static CompatConfig getDefaultConfig(){
CompatConfig cfg = new NewConfig(null);
cfg.set("plugins.force-enable-later", new LinkedList<String>()); // ConfigUtil.asList(new String[]{ "NoCheatPlus" }));
cfg.set("plugins.ensure-enable", new LinkedList<String>()); // ConfigUtil.asList(new String[]{ "WorldGuard" }));
cfg.set("plugins.bedrock-extempt-checks", ConfigUtil.asList(new String[]{
"BLOCKINTERACT_VISIBLE",
"BLOCKINTERACT_DIRECTION",
"BLOCKINTERACT_REACH",
"BLOCKBREAK_DIRECTION",
"BLOCKBREAK_NOSWING",
"BLOCKBREAK_REACH",
"BLOCKPLACE_NOSWING",
"BLOCKPLACE_DIRECTION",
"BLOCKPLACE_REACH",
"BLOCKPLACE_SCAFFOLD",
"FIGHT_DIRECTION",
}));
cfg.set("hooks.prevent-add", new LinkedList<String>());
cfg.set("configversion", configVersion);
return cfg;
}
public static boolean addDefaults(CompatConfig cfg){
boolean changed = false;
if (cfg.getInt("configversion", 0) == 0){
cfg.remove("plugins");
cfg.set("configversion", configVersion);
changed = true;
}
if (cfg.getInt("configversion", 0) <= 1){
if (cfg.getDouble("hooks.set-speed.fly-speed", 0.1) != 0.1){
changed = true;
cfg.set("hooks.set-speed.fly-speed", 0.1);
Bukkit.getLogger().warning("[cncp] Reset fly-speed for the set-speed hook to 0.1 (default) as a safety measure.");
}
if (cfg.getDouble("hooks.set-speed.walk-speed", 0.2) != 0.2){
changed = true;
cfg.set("hooks.set-speed.walk-speed", 0.2);
Bukkit.getLogger().warning("[cncp] Reset walk-speed for the set-speed hook to 0.2 (default) as a safety measure.");
}
}
if (ConfigUtil.forceDefaults(getDefaultConfig(), cfg)) changed = true;
if (cfg.getInt("configversion", 0) != configVersion){
cfg.set("configversion", configVersion);
changed = true;
}
return changed;
}
public boolean fromConfig(CompatConfig cfg){
// Settings ref = new Settings();
// plugins to force enabling after this plugin.
ConfigUtil.readStringSetFromList(cfg, "plugins.force-enable-later", forceEnableLater, true, true, false);
ConfigUtil.readStringSetFromList(cfg, "plugins.ensure-enable", loadPlugins, true, true, false);
ConfigUtil.readCheckTypeSetFromList(cfg, "plugins.bedrock-extempt-checks", extemptChecks, true, true, true);
// General
ConfigUtil.readStringSetFromList(cfg, "hooks.prevent-add", preventAddHooks, true, true, false);
return true;
}
public void clear() {
forceEnableLater.clear();
}
}
package me.asofold.bpl.cncp.config;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;
import org.bukkit.Bukkit;
import fr.neatmonster.nocheatplus.checks.CheckType;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.config.compatlayer.NewConfig;
public class Settings {
public static final int configVersion = 2;
public Set<String> forceEnableLater = new LinkedHashSet<String>();
public Set<String> loadPlugins = new LinkedHashSet<String>();
public Set<CheckType> extemptChecks = new LinkedHashSet<CheckType>();
public static Set<String> preventAddHooks = new HashSet<String>();
public static CompatConfig getDefaultConfig(){
CompatConfig cfg = new NewConfig(null);
cfg.set("plugins.force-enable-later", new LinkedList<String>()); // ConfigUtil.asList(new String[]{ "NoCheatPlus" }));
cfg.set("plugins.ensure-enable", new LinkedList<String>()); // ConfigUtil.asList(new String[]{ "WorldGuard" }));
cfg.set("plugins.bedrock-extempt-checks", ConfigUtil.asList(new String[]{
"BLOCKINTERACT_VISIBLE",
"BLOCKINTERACT_DIRECTION",
"BLOCKINTERACT_REACH",
"BLOCKBREAK_DIRECTION",
"BLOCKBREAK_NOSWING",
"BLOCKBREAK_REACH",
"BLOCKPLACE_NOSWING",
"BLOCKPLACE_DIRECTION",
"BLOCKPLACE_REACH",
"BLOCKPLACE_SCAFFOLD",
"FIGHT_DIRECTION",
}));
cfg.set("hooks.prevent-add", new LinkedList<String>());
cfg.set("configversion", configVersion);
return cfg;
}
public static boolean addDefaults(CompatConfig cfg){
boolean changed = false;
if (cfg.getInt("configversion", 0) == 0){
cfg.remove("plugins");
cfg.set("configversion", configVersion);
changed = true;
}
if (cfg.getInt("configversion", 0) <= 1){
if (cfg.getDouble("hooks.set-speed.fly-speed", 0.1) != 0.1){
changed = true;
cfg.set("hooks.set-speed.fly-speed", 0.1);
Bukkit.getLogger().warning("[cncp] Reset fly-speed for the set-speed hook to 0.1 (default) as a safety measure.");
}
if (cfg.getDouble("hooks.set-speed.walk-speed", 0.2) != 0.2){
changed = true;
cfg.set("hooks.set-speed.walk-speed", 0.2);
Bukkit.getLogger().warning("[cncp] Reset walk-speed for the set-speed hook to 0.2 (default) as a safety measure.");
}
}
if (ConfigUtil.forceDefaults(getDefaultConfig(), cfg)) changed = true;
if (cfg.getInt("configversion", 0) != configVersion){
cfg.set("configversion", configVersion);
changed = true;
}
return changed;
}
public boolean fromConfig(CompatConfig cfg){
// Settings ref = new Settings();
// plugins to force enabling after this plugin.
ConfigUtil.readStringSetFromList(cfg, "plugins.force-enable-later", forceEnableLater, true, true, false);
ConfigUtil.readStringSetFromList(cfg, "plugins.ensure-enable", loadPlugins, true, true, false);
ConfigUtil.readCheckTypeSetFromList(cfg, "plugins.bedrock-extempt-checks", extemptChecks, true, true, true);
// General
ConfigUtil.readStringSetFromList(cfg, "hooks.prevent-add", preventAddHooks, true, true, false);
return true;
}
public void clear() {
forceEnableLater.clear();
}
}

View File

@ -1,213 +1,213 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Some generic checks and stuff using getString, hasEntry, getStringList, ...
* @author mc_dev
*
*/
public abstract class AbstractConfig implements CompatConfig {
protected char sep = '.';
@Override
public Boolean getBoolean(String path, Boolean defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
// return Boolean.parseBoolean(val);
String t = val.trim().toLowerCase();
if ( t.equals("true")) return true;
else if ( t.equals("false")) return false;
else return defaultValue;
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Double getDouble(String path, Double defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Double.parseDouble(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Long getLong(String path, Long defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Long.parseLong(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Integer getInt(String path, Integer defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Integer.parseInt(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public List<Integer> getIntList(String path, List<Integer> defaultValue){
if ( !hasEntry(path) ) return defaultValue;
List<String> strings = getStringList(path, null);
if ( strings == null ) return defaultValue;
List<Integer> out = new LinkedList<Integer>();
for ( String s : strings){
try{
out.add(Integer.parseInt(s));
} catch(NumberFormatException exc){
// ignore
}
}
return out;
}
@Override
public List<Double> getDoubleList(String path, List<Double> defaultValue) {
if ( !hasEntry(path) ) return defaultValue;
List<String> strings = getStringList(path, null);
if ( strings == null ) return defaultValue;
List<Double> out = new LinkedList<Double>();
for ( String s : strings){
try{
out.add(Double.parseDouble(s));
} catch(NumberFormatException exc){
// ignore
}
}
return out;
}
@Override
public Set<String> getStringKeys(String path, boolean deep) {
if (deep) return getStringKeysDeep(path);
Set<String> keys = new HashSet<String>();
keys.addAll(getStringKeys(path));
return keys;
}
@Override
public Set<String> getStringKeysDeep(String path) {
// NOTE: pretty inefficient, but aimed at seldomly read sections.
Map<String, Object> values = getValuesDeep();
Set<String> out = new HashSet<String>();
final int len = path.length();
for (String key : values.keySet()){
if (!key.startsWith(path)) continue;
else if (key.length() == len) continue;
else if (key.charAt(len) == sep) out.add(key);
}
return out;
}
@Override
public Object get(String path, Object defaultValue) {
return getProperty(path, defaultValue);
}
@Override
public void set(String path, Object value) {
setProperty(path, value);
}
@Override
public void remove(String path) {
removeProperty(path);
}
@Override
public Boolean getBoolean(String path) {
return getBoolean(path, null);
}
@Override
public Double getDouble(String path) {
return getDouble(path, null);
}
@Override
public List<Double> getDoubleList(String path) {
return getDoubleList(path, null);
}
@Override
public Integer getInt(String path) {
return getInt(path, null);
}
@Override
public List<Integer> getIntList(String path) {
return getIntList(path, null);
}
@Override
public Integer getInteger(String path) {
return getInt(path, null);
}
@Override
public List<Integer> getIntegerList(String path) {
return getIntList(path, null);
}
@Override
public String getString(String path) {
return getString(path, null);
}
@Override
public List<String> getStringList(String path) {
return getStringList(path, null);
}
@Override
public Object get(String path) {
return getProperty(path, null);
}
@Override
public Object getProperty(String path) {
return getProperty(path, null);
}
@Override
public boolean contains(String path) {
return hasEntry(path);
}
@Override
public Integer getInteger(String path, Integer defaultValue) {
return getInt(path, defaultValue);
}
@Override
public List<Integer> getIntegerList(String path, List<Integer> defaultValue) {
return getIntList(path, defaultValue);
}
@Override
public Long getLong(String path) {
return getLong(path, null);
}
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Some generic checks and stuff using getString, hasEntry, getStringList, ...
* @author mc_dev
*
*/
public abstract class AbstractConfig implements CompatConfig {
protected char sep = '.';
@Override
public Boolean getBoolean(String path, Boolean defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
// return Boolean.parseBoolean(val);
String t = val.trim().toLowerCase();
if ( t.equals("true")) return true;
else if ( t.equals("false")) return false;
else return defaultValue;
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Double getDouble(String path, Double defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Double.parseDouble(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Long getLong(String path, Long defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Long.parseLong(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public Integer getInt(String path, Integer defaultValue) {
String val = getString(path, null);
if ( val == null ) return defaultValue;
try{
return Integer.parseInt(val);
} catch( NumberFormatException exc){
return defaultValue;
}
}
@Override
public List<Integer> getIntList(String path, List<Integer> defaultValue){
if ( !hasEntry(path) ) return defaultValue;
List<String> strings = getStringList(path, null);
if ( strings == null ) return defaultValue;
List<Integer> out = new LinkedList<Integer>();
for ( String s : strings){
try{
out.add(Integer.parseInt(s));
} catch(NumberFormatException exc){
// ignore
}
}
return out;
}
@Override
public List<Double> getDoubleList(String path, List<Double> defaultValue) {
if ( !hasEntry(path) ) return defaultValue;
List<String> strings = getStringList(path, null);
if ( strings == null ) return defaultValue;
List<Double> out = new LinkedList<Double>();
for ( String s : strings){
try{
out.add(Double.parseDouble(s));
} catch(NumberFormatException exc){
// ignore
}
}
return out;
}
@Override
public Set<String> getStringKeys(String path, boolean deep) {
if (deep) return getStringKeysDeep(path);
Set<String> keys = new HashSet<String>();
keys.addAll(getStringKeys(path));
return keys;
}
@Override
public Set<String> getStringKeysDeep(String path) {
// NOTE: pretty inefficient, but aimed at seldomly read sections.
Map<String, Object> values = getValuesDeep();
Set<String> out = new HashSet<String>();
final int len = path.length();
for (String key : values.keySet()){
if (!key.startsWith(path)) continue;
else if (key.length() == len) continue;
else if (key.charAt(len) == sep) out.add(key);
}
return out;
}
@Override
public Object get(String path, Object defaultValue) {
return getProperty(path, defaultValue);
}
@Override
public void set(String path, Object value) {
setProperty(path, value);
}
@Override
public void remove(String path) {
removeProperty(path);
}
@Override
public Boolean getBoolean(String path) {
return getBoolean(path, null);
}
@Override
public Double getDouble(String path) {
return getDouble(path, null);
}
@Override
public List<Double> getDoubleList(String path) {
return getDoubleList(path, null);
}
@Override
public Integer getInt(String path) {
return getInt(path, null);
}
@Override
public List<Integer> getIntList(String path) {
return getIntList(path, null);
}
@Override
public Integer getInteger(String path) {
return getInt(path, null);
}
@Override
public List<Integer> getIntegerList(String path) {
return getIntList(path, null);
}
@Override
public String getString(String path) {
return getString(path, null);
}
@Override
public List<String> getStringList(String path) {
return getStringList(path, null);
}
@Override
public Object get(String path) {
return getProperty(path, null);
}
@Override
public Object getProperty(String path) {
return getProperty(path, null);
}
@Override
public boolean contains(String path) {
return hasEntry(path);
}
@Override
public Integer getInteger(String path, Integer defaultValue) {
return getInt(path, defaultValue);
}
@Override
public List<Integer> getIntegerList(String path, List<Integer> defaultValue) {
return getIntList(path, defaultValue);
}
@Override
public Long getLong(String path) {
return getLong(path, null);
}
}

View File

@ -1,237 +1,237 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationOptions;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
public abstract class AbstractNewConfig extends AbstractConfig {
File file = null;
MemoryConfiguration config = null;
public AbstractNewConfig(File file){
setFile(file);
}
public void setFile(File file) {
this.file = file;
this.config = new MemoryConfiguration();
setOptions(config);
}
@Override
public boolean hasEntry(String path) {
return config.contains(path) || (config.get(path) != null);
}
@Override
public String getString(String path, String defaultValue) {
if (!hasEntry(path)) return defaultValue;
return config.getString(path, defaultValue);
}
@Override
public List<String> getStringKeys(String path) {
// TODO policy: only strings or all keys as strings ?
List<String> out = new LinkedList<String>();
List<Object> keys = getKeys(path);
if ( keys == null ) return out;
for ( Object obj : keys){
if ( obj instanceof String ) out.add((String) obj);
else{
try{
out.add(obj.toString());
} catch ( Throwable t){
// ignore.
}
}
}
return out;
}
@Override
public List<Object> getKeys(String path) {
List<Object> out = new LinkedList<Object>();
Set<String> keys;
if ( path == null) keys = config.getKeys(false);
else{
ConfigurationSection sec = config.getConfigurationSection(path);
if (sec == null) return out;
keys = sec.getKeys(false);
}
if ( keys == null) return out;
out.addAll(keys);
return out;
}
@Override
public List<Object> getKeys() {
return getKeys(null);
}
@Override
public Object getProperty(String path, Object defaultValue) {
Object obj = config.get(path);
if ( obj == null ) return defaultValue;
else return obj;
}
@Override
public List<String> getStringKeys() {
return getStringKeys(null);
}
@Override
public void setProperty(String path, Object obj) {
config.set(path, obj);
}
@Override
public List<String> getStringList(String path, List<String> defaultValue) {
if ( !hasEntry(path)) return defaultValue;
List<String> out = new LinkedList<String>();
List<String> entries = config.getStringList(path);
if ( entries == null ) return defaultValue;
for ( String entry : entries){
if ( entry instanceof String) out.add(entry);
else{
try{
out.add(entry.toString());
} catch (Throwable t){
// ignore
}
}
}
return out;
}
@Override
public void removeProperty(String path) {
if (path.startsWith(".")) path = path.substring(1);
// VERY EXPENSIVE
MemoryConfiguration temp = new MemoryConfiguration();
setOptions(temp);
Map<String, Object> values = config.getValues(true);
if (values.containsKey(path)) values.remove(path);
else{
final String altPath = "."+path;
if (values.containsKey(altPath)) values.remove(altPath);
}
for ( String _p : values.keySet()){
Object v = values.get(_p);
if (v == null) continue;
else if (v instanceof ConfigurationSection) continue;
String p;
if (_p.startsWith(".")) p = _p.substring(1);
else p = _p;
if (p.startsWith(path)) continue;
temp.set(p, v);
}
config = temp;
}
@Override
public Boolean getBoolean(String path, Boolean defaultValue) {
if (!config.contains(path)) return defaultValue;
String val = config.getString(path, null);
if (val != null){
if (val.equalsIgnoreCase("true")) return true;
else if (val.equalsIgnoreCase("false")) return false;
else return defaultValue;
}
Boolean res = defaultValue;
if ( val == null ){
if ( defaultValue == null) defaultValue = false;
res = config.getBoolean(path, defaultValue);
}
return res;
}
@Override
public Double getDouble(String path, Double defaultValue) {
if (!config.contains(path)) return defaultValue;
Double res = super.getDouble(path, null);
if ( res == null ) res = config.getDouble(path, ConfigUtil.canaryDouble);
if ( res == ConfigUtil.canaryDouble) return defaultValue;
return res;
}
@Override
public Long getLong(String path, Long defaultValue) {
if (!config.contains(path)) return defaultValue;
Long res = super.getLong(path, null);
if ( res == null ) res = config.getLong(path, ConfigUtil.canaryLong);
if ( res == ConfigUtil.canaryLong) return defaultValue;
return res;
}
@Override
public Integer getInt(String path, Integer defaultValue) {
if (!config.contains(path)) return defaultValue;
Integer res = super.getInt(path, null);
if ( res == null ) res = config.getInt(path, ConfigUtil.canaryInt);
if ( res == ConfigUtil.canaryInt) return defaultValue;
return res;
}
@Override
public List<Integer> getIntList(String path, List<Integer> defaultValue) {
// TODO Auto-generated method stub
return super.getIntList(path, defaultValue);
}
@Override
public List<Double> getDoubleList(String path, List<Double> defaultValue) {
// TODO Auto-generated method stub
return super.getDoubleList(path, defaultValue);
}
void addAll(Configuration source, Configuration target){
Map<String, Object> all = source.getValues(true);
for ( String path: all.keySet()){
target.set(path, source.get(path));
}
}
void setOptions(Configuration cfg){
ConfigurationOptions opt = cfg.options();
opt.pathSeparator(this.sep);
//opt.copyDefaults(true);
}
@Override
public boolean setPathSeparatorChar(char sep) {
this.sep = sep;
setOptions(config);
return true;
}
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationOptions;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
public abstract class AbstractNewConfig extends AbstractConfig {
File file = null;
MemoryConfiguration config = null;
public AbstractNewConfig(File file){
setFile(file);
}
public void setFile(File file) {
this.file = file;
this.config = new MemoryConfiguration();
setOptions(config);
}
@Override
public boolean hasEntry(String path) {
return config.contains(path) || (config.get(path) != null);
}
@Override
public String getString(String path, String defaultValue) {
if (!hasEntry(path)) return defaultValue;
return config.getString(path, defaultValue);
}
@Override
public List<String> getStringKeys(String path) {
// TODO policy: only strings or all keys as strings ?
List<String> out = new LinkedList<String>();
List<Object> keys = getKeys(path);
if ( keys == null ) return out;
for ( Object obj : keys){
if ( obj instanceof String ) out.add((String) obj);
else{
try{
out.add(obj.toString());
} catch ( Throwable t){
// ignore.
}
}
}
return out;
}
@Override
public List<Object> getKeys(String path) {
List<Object> out = new LinkedList<Object>();
Set<String> keys;
if ( path == null) keys = config.getKeys(false);
else{
ConfigurationSection sec = config.getConfigurationSection(path);
if (sec == null) return out;
keys = sec.getKeys(false);
}
if ( keys == null) return out;
out.addAll(keys);
return out;
}
@Override
public List<Object> getKeys() {
return getKeys(null);
}
@Override
public Object getProperty(String path, Object defaultValue) {
Object obj = config.get(path);
if ( obj == null ) return defaultValue;
else return obj;
}
@Override
public List<String> getStringKeys() {
return getStringKeys(null);
}
@Override
public void setProperty(String path, Object obj) {
config.set(path, obj);
}
@Override
public List<String> getStringList(String path, List<String> defaultValue) {
if ( !hasEntry(path)) return defaultValue;
List<String> out = new LinkedList<String>();
List<String> entries = config.getStringList(path);
if ( entries == null ) return defaultValue;
for ( String entry : entries){
if ( entry instanceof String) out.add(entry);
else{
try{
out.add(entry.toString());
} catch (Throwable t){
// ignore
}
}
}
return out;
}
@Override
public void removeProperty(String path) {
if (path.startsWith(".")) path = path.substring(1);
// VERY EXPENSIVE
MemoryConfiguration temp = new MemoryConfiguration();
setOptions(temp);
Map<String, Object> values = config.getValues(true);
if (values.containsKey(path)) values.remove(path);
else{
final String altPath = "."+path;
if (values.containsKey(altPath)) values.remove(altPath);
}
for ( String _p : values.keySet()){
Object v = values.get(_p);
if (v == null) continue;
else if (v instanceof ConfigurationSection) continue;
String p;
if (_p.startsWith(".")) p = _p.substring(1);
else p = _p;
if (p.startsWith(path)) continue;
temp.set(p, v);
}
config = temp;
}
@Override
public Boolean getBoolean(String path, Boolean defaultValue) {
if (!config.contains(path)) return defaultValue;
String val = config.getString(path, null);
if (val != null){
if (val.equalsIgnoreCase("true")) return true;
else if (val.equalsIgnoreCase("false")) return false;
else return defaultValue;
}
Boolean res = defaultValue;
if ( val == null ){
if ( defaultValue == null) defaultValue = false;
res = config.getBoolean(path, defaultValue);
}
return res;
}
@Override
public Double getDouble(String path, Double defaultValue) {
if (!config.contains(path)) return defaultValue;
Double res = super.getDouble(path, null);
if ( res == null ) res = config.getDouble(path, ConfigUtil.canaryDouble);
if ( res == ConfigUtil.canaryDouble) return defaultValue;
return res;
}
@Override
public Long getLong(String path, Long defaultValue) {
if (!config.contains(path)) return defaultValue;
Long res = super.getLong(path, null);
if ( res == null ) res = config.getLong(path, ConfigUtil.canaryLong);
if ( res == ConfigUtil.canaryLong) return defaultValue;
return res;
}
@Override
public Integer getInt(String path, Integer defaultValue) {
if (!config.contains(path)) return defaultValue;
Integer res = super.getInt(path, null);
if ( res == null ) res = config.getInt(path, ConfigUtil.canaryInt);
if ( res == ConfigUtil.canaryInt) return defaultValue;
return res;
}
@Override
public List<Integer> getIntList(String path, List<Integer> defaultValue) {
// TODO Auto-generated method stub
return super.getIntList(path, defaultValue);
}
@Override
public List<Double> getDoubleList(String path, List<Double> defaultValue) {
// TODO Auto-generated method stub
return super.getDoubleList(path, defaultValue);
}
void addAll(Configuration source, Configuration target){
Map<String, Object> all = source.getValues(true);
for ( String path: all.keySet()){
target.set(path, source.get(path));
}
}
void setOptions(Configuration cfg){
ConfigurationOptions opt = cfg.options();
opt.pathSeparator(this.sep);
//opt.copyDefaults(true);
}
@Override
public boolean setPathSeparatorChar(char sep) {
this.sep = sep;
setOptions(config);
return true;
}
}

View File

@ -1,155 +1,155 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* CONVENTIONS:
* - Return strings if objects can be made strings.
* - No exceptions, rather leave elements out of lists.
* - Lists of length 0 and null can not always be distinguished (?->extra safe wrapper ?)
* - All contents are treated alike, even if given as a string (!): true and 'true', 1 and '1'
* @author mc_dev
*
*/
public interface CompatConfig {
// Boolean
/**
* Only accepts true and false , 'true' and 'false'.
* @param path
* @param defaultValue
* @return
*/
public Boolean getBoolean(String path, Boolean defaultValue);
public Boolean getBoolean(String path);
// Long
public Long getLong(String path);
public Long getLong(String path, Long defaultValue);
// Double
public Double getDouble(String path);
public Double getDouble(String path, Double defaultValue);
public List<Double> getDoubleList(String path);
public List<Double> getDoubleList(String path , List<Double> defaultValue);
// Integer (abbreviation)
public Integer getInt(String path);
public Integer getInt(String path, Integer defaultValue);
public List<Integer> getIntList(String path);
public List<Integer> getIntList(String path, List<Integer> defaultValue);
// Integer (full name)
public Integer getInteger(String path);
public Integer getInteger(String path, Integer defaultValue);
public List<Integer> getIntegerList(String path);
public List<Integer> getIntegerList(String path, List<Integer> defaultValue);
// String
public String getString(String path);
public String getString(String path, String defaultValue);
public List<String> getStringList(String path);
public List<String> getStringList(String path, List<String> defaultValue);
// Generic methods:
public Object get(String path);
public Object get(String path, Object defaultValue);
public Object getProperty(String path);
public Object getProperty(String path, Object defaultValue);
public void set(String path, Object value);
public void setProperty(String path, Object value);
/**
* Remove a path (would also remove sub sections, unless for path naming problems).
* @param path
*/
public void remove(String path);
/**
* Works same as remove(path): removes properties and sections alike.
* @param path
*/
public void removeProperty(String path);
// Contains/has
public boolean hasEntry(String path);
public boolean contains(String path);
// Keys (Object): [possibly deprecated]
/**
* @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(String path);
* @param path
* @return
*/
public List<Object> getKeys(String path);
/**
* @deprecated Seems not to be supported anymore by new configuration, use getStringKeys();
* @return
*/
public List<Object> getKeys();
// Keys (String):
/**
*
* @return never null
*/
public List<String> getStringKeys();
public List<String> getStringKeys(String path);
/**
* Get all keys from the section (deep or shallow).
* @param path
* @param deep
* @return Never null.
*/
public Set<String> getStringKeys(String path, boolean deep);
/**
* convenience method.
* @param path
* @return never null
*
*/
public Set<String> getStringKeysDeep(String path);
// Values:
/**
* Equivalent to new config: values(true)
* @return
*/
public Map<String, Object> getValuesDeep();
// Technical / IO:
/**
* False if not supported.
* @param sep
* @return
*/
public boolean setPathSeparatorChar(char sep);
public void load();
public boolean save();
/**
* Clear all contents.
*/
public void clear();
/**
* Return a YAML-String representation of the contents, null if not supported.
* @return null if not supported.
*/
public String getYAMLString();
/**
* Add all entries from the YAML-String representation to the configuration, forget or clear all previous entries.
* @return
*/
public boolean fromYamlString(String input);
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* CONVENTIONS:
* - Return strings if objects can be made strings.
* - No exceptions, rather leave elements out of lists.
* - Lists of length 0 and null can not always be distinguished (?->extra safe wrapper ?)
* - All contents are treated alike, even if given as a string (!): true and 'true', 1 and '1'
* @author mc_dev
*
*/
public interface CompatConfig {
// Boolean
/**
* Only accepts true and false , 'true' and 'false'.
* @param path
* @param defaultValue
* @return
*/
public Boolean getBoolean(String path, Boolean defaultValue);
public Boolean getBoolean(String path);
// Long
public Long getLong(String path);
public Long getLong(String path, Long defaultValue);
// Double
public Double getDouble(String path);
public Double getDouble(String path, Double defaultValue);
public List<Double> getDoubleList(String path);
public List<Double> getDoubleList(String path , List<Double> defaultValue);
// Integer (abbreviation)
public Integer getInt(String path);
public Integer getInt(String path, Integer defaultValue);
public List<Integer> getIntList(String path);
public List<Integer> getIntList(String path, List<Integer> defaultValue);
// Integer (full name)
public Integer getInteger(String path);
public Integer getInteger(String path, Integer defaultValue);
public List<Integer> getIntegerList(String path);
public List<Integer> getIntegerList(String path, List<Integer> defaultValue);
// String
public String getString(String path);
public String getString(String path, String defaultValue);
public List<String> getStringList(String path);
public List<String> getStringList(String path, List<String> defaultValue);
// Generic methods:
public Object get(String path);
public Object get(String path, Object defaultValue);
public Object getProperty(String path);
public Object getProperty(String path, Object defaultValue);
public void set(String path, Object value);
public void setProperty(String path, Object value);
/**
* Remove a path (would also remove sub sections, unless for path naming problems).
* @param path
*/
public void remove(String path);
/**
* Works same as remove(path): removes properties and sections alike.
* @param path
*/
public void removeProperty(String path);
// Contains/has
public boolean hasEntry(String path);
public boolean contains(String path);
// Keys (Object): [possibly deprecated]
/**
* @deprecated Seems not to be supported anymore by new configuration, use getStringKeys(String path);
* @param path
* @return
*/
public List<Object> getKeys(String path);
/**
* @deprecated Seems not to be supported anymore by new configuration, use getStringKeys();
* @return
*/
public List<Object> getKeys();
// Keys (String):
/**
*
* @return never null
*/
public List<String> getStringKeys();
public List<String> getStringKeys(String path);
/**
* Get all keys from the section (deep or shallow).
* @param path
* @param deep
* @return Never null.
*/
public Set<String> getStringKeys(String path, boolean deep);
/**
* convenience method.
* @param path
* @return never null
*
*/
public Set<String> getStringKeysDeep(String path);
// Values:
/**
* Equivalent to new config: values(true)
* @return
*/
public Map<String, Object> getValuesDeep();
// Technical / IO:
/**
* False if not supported.
* @param sep
* @return
*/
public boolean setPathSeparatorChar(char sep);
public void load();
public boolean save();
/**
* Clear all contents.
*/
public void clear();
/**
* Return a YAML-String representation of the contents, null if not supported.
* @return null if not supported.
*/
public String getYAMLString();
/**
* Add all entries from the YAML-String representation to the configuration, forget or clear all previous entries.
* @return
*/
public boolean fromYamlString(String input);
}

View File

@ -1,56 +1,56 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
public class CompatConfigFactory {
public static final String version = "0.8.1";
/**
* Attempt to get a working file configuration.<br>
* This is not fit for fast processing.<br>
* Use getDBConfig to use this with a database.<br>
* @param file May be null (then memory is used).
* @return null if fails.
*/
public static final CompatConfig getConfig(File file){
CompatConfig out = null;
// TODO: add more (latest API)
// try{
// return new OldConfig(file);
// } catch (Throwable t){
// }
try{
return new NewConfig(file);
} catch (Throwable t){
}
return out;
}
// public static final CompatConfig getOldConfig(File file){
// return new OldConfig(file);
// }
public static final CompatConfig getNewConfig(File file){
return new NewConfig(file);
}
// /**
// * Get a ebeans based database config (!).
// * @param file
// * @return
// */
// public static final CompatConfig getDBConfig(EbeanServer server, String dbKey){
// try{
// return new SnakeDBConfig(server, dbKey);
// } catch (Throwable t){
//
// }
// return new DBConfig(server, dbKey);
// }
// TODO: add setup helpers (!)
// TODO: add conversion helpers (!)
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
public class CompatConfigFactory {
public static final String version = "0.8.1";
/**
* Attempt to get a working file configuration.<br>
* This is not fit for fast processing.<br>
* Use getDBConfig to use this with a database.<br>
* @param file May be null (then memory is used).
* @return null if fails.
*/
public static final CompatConfig getConfig(File file){
CompatConfig out = null;
// TODO: add more (latest API)
// try{
// return new OldConfig(file);
// } catch (Throwable t){
// }
try{
return new NewConfig(file);
} catch (Throwable t){
}
return out;
}
// public static final CompatConfig getOldConfig(File file){
// return new OldConfig(file);
// }
public static final CompatConfig getNewConfig(File file){
return new NewConfig(file);
}
// /**
// * Get a ebeans based database config (!).
// * @param file
// * @return
// */
// public static final CompatConfig getDBConfig(EbeanServer server, String dbKey){
// try{
// return new SnakeDBConfig(server, dbKey);
// } catch (Throwable t){
//
// }
// return new DBConfig(server, dbKey);
// }
// TODO: add setup helpers (!)
// TODO: add conversion helpers (!)
}

View File

@ -1,224 +1,224 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class ConfigUtil {
public static final int canaryInt = Integer.MIN_VALUE +7;
public static final long canaryLong = Long.MIN_VALUE + 7L;
public static final double canaryDouble = -Double.MAX_VALUE + 1.2593;
public static String stringPath( String path){
return stringPath(path, '.');
}
public static String stringPath( String path , char sep ){
String useSep = (sep=='.')?"\\.":""+sep;
String[] split = path.split(useSep);
StringBuilder builder = new StringBuilder();
builder.append(stringPart(split[0]));
for (int i = 1; i<split.length; i++){
builder.append(sep+stringPart(split[i]));
}
return builder.toString();
}
/**
* Aimed at numbers in paths.
* @param cfg
* @param path
* @return
*/
public static String bestPath(CompatConfig cfg, String path){
return bestPath(cfg, path, '.');
}
/**
* Aimed at numbers in paths.
* @param cfg
* @param path
* @param sep
* @return
*/
public static String bestPath(CompatConfig cfg, String path, char sep){
String useSep = (sep=='.')?"\\.":""+sep;
String[] split = path.split(useSep);
String res;
if (cfg.hasEntry(split[0]) )res = split[0];
else{
res = stringPart(split[0]);
if ( !cfg.hasEntry(res)) return path;
}
for (int i = 1; i<split.length; i++){
if (cfg.hasEntry(res+sep+split[i]) ) res += sep+split[i];
else{
res += sep+stringPart(split[i]);
if ( !cfg.hasEntry(res)) return path;
}
}
return res;
}
public static String stringPart(String input){
try{
Double.parseDouble(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
try{
Long.parseLong(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
try{
Integer.parseInt(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
return input;
}
public static boolean forceDefaults(CompatConfig defaults, CompatConfig config){
Map<String ,Object> all = defaults.getValuesDeep();
boolean changed = false;
for ( String path : all.keySet()){
if ( !config.hasEntry(path)){
config.setProperty(path, defaults.getProperty(path, null));
changed = true;
}
}
return changed;
}
/**
* Add StringList entries to a set.
* @param cfg
* @param path
* @param set
* @param clear If to clear the set.
* @param trim
* @param lowerCase
*/
public static void readStringSetFromList(CompatConfig cfg, String path, Set<String> set, boolean clear, boolean trim, boolean lowerCase){
if (clear) set.clear();
List<String> tempList = cfg.getStringList(path , null);
if (tempList != null){
for (String entry : tempList){
if (trim) entry = entry.trim();
if (lowerCase) entry = entry.toLowerCase();
set.add(entry);
}
}
}
/**
* Add StringList entries to a set.
* @param cfg
* @param path
* @param set
* @param clear If to clear the set.
* @param trim
* @param upperCase
*/
public static void readCheckTypeSetFromList(CompatConfig cfg, String path, Set<CheckType> set, boolean clear, boolean trim, boolean upperCase){
if (clear) set.clear();
List<String> tempList = cfg.getStringList(path , null);
if (tempList != null){
for (String entry : tempList) {
if (trim) entry = entry.trim();
if (upperCase) entry = entry.toUpperCase();
try {
final CheckType checkType = CheckType.valueOf(entry);
set.add(checkType);
} catch (Exception e) {
System.out.println("[cncp] Unknow check " + entry + " is. Skipping!");
}
}
}
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final <T> List<T> asList(final T[] input){
final List<T> out = new ArrayList<T>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Integer> asList(final int[] input){
final List<Integer> out = new ArrayList<Integer>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Long> asList(final long[] input){
final List<Long> out = new ArrayList<Long>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Double> asList(final double[] input){
final List<Double> out = new ArrayList<Double>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Float> asList(final float[] input){
final List<Float> out = new ArrayList<Float>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Boolean> asList(final boolean[] input){
final List<Boolean> out = new ArrayList<Boolean>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class ConfigUtil {
public static final int canaryInt = Integer.MIN_VALUE +7;
public static final long canaryLong = Long.MIN_VALUE + 7L;
public static final double canaryDouble = -Double.MAX_VALUE + 1.2593;
public static String stringPath( String path){
return stringPath(path, '.');
}
public static String stringPath( String path , char sep ){
String useSep = (sep=='.')?"\\.":""+sep;
String[] split = path.split(useSep);
StringBuilder builder = new StringBuilder();
builder.append(stringPart(split[0]));
for (int i = 1; i<split.length; i++){
builder.append(sep+stringPart(split[i]));
}
return builder.toString();
}
/**
* Aimed at numbers in paths.
* @param cfg
* @param path
* @return
*/
public static String bestPath(CompatConfig cfg, String path){
return bestPath(cfg, path, '.');
}
/**
* Aimed at numbers in paths.
* @param cfg
* @param path
* @param sep
* @return
*/
public static String bestPath(CompatConfig cfg, String path, char sep){
String useSep = (sep=='.')?"\\.":""+sep;
String[] split = path.split(useSep);
String res;
if (cfg.hasEntry(split[0]) )res = split[0];
else{
res = stringPart(split[0]);
if ( !cfg.hasEntry(res)) return path;
}
for (int i = 1; i<split.length; i++){
if (cfg.hasEntry(res+sep+split[i]) ) res += sep+split[i];
else{
res += sep+stringPart(split[i]);
if ( !cfg.hasEntry(res)) return path;
}
}
return res;
}
public static String stringPart(String input){
try{
Double.parseDouble(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
try{
Long.parseLong(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
try{
Integer.parseInt(input);
return "'"+input+"'";
} catch (NumberFormatException e){
}
return input;
}
public static boolean forceDefaults(CompatConfig defaults, CompatConfig config){
Map<String ,Object> all = defaults.getValuesDeep();
boolean changed = false;
for ( String path : all.keySet()){
if ( !config.hasEntry(path)){
config.setProperty(path, defaults.getProperty(path, null));
changed = true;
}
}
return changed;
}
/**
* Add StringList entries to a set.
* @param cfg
* @param path
* @param set
* @param clear If to clear the set.
* @param trim
* @param lowerCase
*/
public static void readStringSetFromList(CompatConfig cfg, String path, Set<String> set, boolean clear, boolean trim, boolean lowerCase){
if (clear) set.clear();
List<String> tempList = cfg.getStringList(path , null);
if (tempList != null){
for (String entry : tempList){
if (trim) entry = entry.trim();
if (lowerCase) entry = entry.toLowerCase();
set.add(entry);
}
}
}
/**
* Add StringList entries to a set.
* @param cfg
* @param path
* @param set
* @param clear If to clear the set.
* @param trim
* @param upperCase
*/
public static void readCheckTypeSetFromList(CompatConfig cfg, String path, Set<CheckType> set, boolean clear, boolean trim, boolean upperCase){
if (clear) set.clear();
List<String> tempList = cfg.getStringList(path , null);
if (tempList != null){
for (String entry : tempList) {
if (trim) entry = entry.trim();
if (upperCase) entry = entry.toUpperCase();
try {
final CheckType checkType = CheckType.valueOf(entry);
set.add(checkType);
} catch (Exception e) {
System.out.println("[cncp] Unknow check " + entry + " is. Skipping!");
}
}
}
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final <T> List<T> asList(final T[] input){
final List<T> out = new ArrayList<T>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Integer> asList(final int[] input){
final List<Integer> out = new ArrayList<Integer>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Long> asList(final long[] input){
final List<Long> out = new ArrayList<Long>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Double> asList(final double[] input){
final List<Double> out = new ArrayList<Double>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Float> asList(final float[] input){
final List<Float> out = new ArrayList<Float>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
/**
* Return an ArrayList.
* @param input
* @return
*/
public static final List<Boolean> asList(final boolean[] input){
final List<Boolean> out = new ArrayList<Boolean>(input.length);
for (int i = 0; i < input.length; i++){
out.add(input[i]);
}
return out;
}
}

View File

@ -1,78 +1,78 @@
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
import java.util.Map;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class NewConfig extends AbstractNewConfig{
public NewConfig(File file) {
super(file);
}
@Override
public void load(){
config = new MemoryConfiguration();
setOptions(config);
FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
setOptions(cfg);
addAll(cfg, config);
}
@Override
public boolean save(){
YamlConfiguration cfg = new YamlConfiguration();
setOptions(cfg);
addAll(config, cfg);
try{
cfg.save(file);
return true;
} catch (Throwable t){
return false;
}
}
@Override
public Map<String, Object> getValuesDeep() {
return config.getValues(true);
}
@Override
public void clear() {
setFile(file);
}
@Override
public String getYAMLString() {
final YamlConfiguration temp = new YamlConfiguration();
addAll(config, temp);
return temp.saveToString();
}
@Override
public boolean fromYamlString(String input) {
final YamlConfiguration temp = new YamlConfiguration();
try {
clear();
temp.loadFromString(input);
addAll(temp, config);
return true;
} catch (InvalidConfigurationException e) {
e.printStackTrace();
return false;
}
}
}
package me.asofold.bpl.cncp.config.compatlayer;
import java.io.File;
import java.util.Map;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class NewConfig extends AbstractNewConfig{
public NewConfig(File file) {
super(file);
}
@Override
public void load(){
config = new MemoryConfiguration();
setOptions(config);
FileConfiguration cfg = YamlConfiguration.loadConfiguration(file);
setOptions(cfg);
addAll(cfg, config);
}
@Override
public boolean save(){
YamlConfiguration cfg = new YamlConfiguration();
setOptions(cfg);
addAll(config, cfg);
try{
cfg.save(file);
return true;
} catch (Throwable t){
return false;
}
}
@Override
public Map<String, Object> getValuesDeep() {
return config.getValues(true);
}
@Override
public void clear() {
setFile(file);
}
@Override
public String getYAMLString() {
final YamlConfiguration temp = new YamlConfiguration();
addAll(config, temp);
return temp.saveToString();
}
@Override
public boolean fromYamlString(String input) {
final YamlConfiguration temp = new YamlConfiguration();
try {
clear();
temp.loadFromString(input);
addAll(temp, config);
return true;
} catch (InvalidConfigurationException e) {
e.printStackTrace();
return false;
}
}
}

View File

@ -1,56 +1,56 @@
package me.asofold.bpl.cncp.hooks;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
/**
* Reads an enabled flag from the config (true by default). The prefix given will be something like "hooks.", so add your hook name to the path like:<br>
* prefix + "myhook.extra-config"
* @author mc_dev
*
*/
public class AbstractConfigurableHook extends AbstractHook implements
ConfigurableHook {
protected final String configPrefix;
protected final String hookName, hookVersion;
protected boolean enabled = true;
public AbstractConfigurableHook(String hookName, String hookVersion, String configPrefix){
this.configPrefix = configPrefix;
this.hookName = hookName;
this.hookVersion = hookVersion;
}
@Override
public String getHookName() {
return hookName;
}
@Override
public String getHookVersion() {
return hookVersion;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}
package me.asofold.bpl.cncp.hooks;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
/**
* Reads an enabled flag from the config (true by default). The prefix given will be something like "hooks.", so add your hook name to the path like:<br>
* prefix + "myhook.extra-config"
* @author mc_dev
*
*/
public class AbstractConfigurableHook extends AbstractHook implements
ConfigurableHook {
protected final String configPrefix;
protected final String hookName, hookVersion;
protected boolean enabled = true;
public AbstractConfigurableHook(String hookName, String hookVersion, String configPrefix){
this.configPrefix = configPrefix;
this.hookName = hookName;
this.hookVersion = hookVersion;
}
@Override
public String getHookName() {
return hookName;
}
@Override
public String getHookVersion() {
return hookVersion;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -1,46 +1,46 @@
package me.asofold.bpl.cncp.hooks;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
/**
* Extend this to make sure that future changes will not break your hooks.<br>
* Probable changes:<br>
* - Adding onReload method.
* @author mc_dev
*
*/
public abstract class AbstractHook implements Hook{
@Override
public CheckType[] getCheckTypes() {
// Handle all CheckEvents (improbable).
return null;
}
@Override
public Listener[] getListeners() {
// No listeners to register with cncp.
return null;
}
@Override
public NCPHook getNCPHook() {
// No hooks to add to NCP.
return null;
}
/**
* Throw a runtime exception if the plugin is not present.
* @param pluginName
*/
protected void assertPluginPresent(String pluginName){
if (Bukkit.getPluginManager().getPlugin(pluginName) == null) throw new RuntimeException("Assertion, " + getHookName() + ": Plugin " + pluginName + " is not present.");
}
}
package me.asofold.bpl.cncp.hooks;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
/**
* Extend this to make sure that future changes will not break your hooks.<br>
* Probable changes:<br>
* - Adding onReload method.
* @author mc_dev
*
*/
public abstract class AbstractHook implements Hook{
@Override
public CheckType[] getCheckTypes() {
// Handle all CheckEvents (improbable).
return null;
}
@Override
public Listener[] getListeners() {
// No listeners to register with cncp.
return null;
}
@Override
public NCPHook getNCPHook() {
// No hooks to add to NCP.
return null;
}
/**
* Throw a runtime exception if the plugin is not present.
* @param pluginName
*/
protected void assertPluginPresent(String pluginName){
if (Bukkit.getPluginManager().getPlugin(pluginName) == null) throw new RuntimeException("Assertion, " + getHookName() + ": Plugin " + pluginName + " is not present.");
}
}

View File

@ -1,48 +1,48 @@
package me.asofold.bpl.cncp.hooks;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
/**
* Interface for hooking into another plugin.<br>
* NOTE: You also have to implement the methods described in NCPHook.<br>
* If you do not use listeners or don't want the prevent-hooks configuration feature
* to take effect, you can also register directly with NCPHookManager.
*
* @author mc_dev
*
*/
public interface Hook{
/**
*
* @return
*/
public String getHookName();
/**
*
* @return
*/
public String getHookVersion();
/**
* The check types to register for, see NCPHookManager for reference, you can use ALL,
*/
public CheckType[] getCheckTypes();
/**
* Get listener instances to be registered with cncp.
* @return null if unused.
*/
public Listener[] getListeners();
/**
* Get the hook to be registered with NCP, the registration will take place after NoCheatPlus has been enabled.
* @return Should always return the same hook or null if not used.
*/
public NCPHook getNCPHook();
}
package me.asofold.bpl.cncp.hooks;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
/**
* Interface for hooking into another plugin.<br>
* NOTE: You also have to implement the methods described in NCPHook.<br>
* If you do not use listeners or don't want the prevent-hooks configuration feature
* to take effect, you can also register directly with NCPHookManager.
*
* @author mc_dev
*
*/
public interface Hook{
/**
*
* @return
*/
public String getHookName();
/**
*
* @return
*/
public String getHookVersion();
/**
* The check types to register for, see NCPHookManager for reference, you can use ALL,
*/
public CheckType[] getCheckTypes();
/**
* Get listener instances to be registered with cncp.
* @return null if unused.
*/
public Listener[] getListeners();
/**
* Get the hook to be registered with NCP, the registration will take place after NoCheatPlus has been enabled.
* @return Should always return the same hook or null if not used.
*/
public NCPHook getNCPHook();
}

View File

@ -1,79 +1,79 @@
package me.asofold.bpl.cncp.hooks.citizens2;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public class HookCitizens2 extends AbstractHook implements ConfigurableHook{
protected Object ncpHook = null;
protected boolean enabled = true;
protected String configPrefix = "citizens2.";
public HookCitizens2(){
assertPluginPresent("Citizens");
CitizensAPI.getNPCRegistry(); // to let it fail for old versions.
}
@Override
public String getHookName() {
return "Citizens2(default)";
}
@Override
public String getHookVersion() {
return "2.2";
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new NCPHook() {
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, IViolationInfo info) {
return CitizensAPI.getNPCRegistry().isNPC(player);
}
@Override
public final String getHookVersion() {
return "2.0";
}
@Override
public final String getHookName() {
return "Citizens2(cncp)";
}
};
}
return (NCPHook) ncpHook;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}
package me.asofold.bpl.cncp.hooks.citizens2;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public class HookCitizens2 extends AbstractHook implements ConfigurableHook{
protected Object ncpHook = null;
protected boolean enabled = true;
protected String configPrefix = "citizens2.";
public HookCitizens2(){
assertPluginPresent("Citizens");
CitizensAPI.getNPCRegistry(); // to let it fail for old versions.
}
@Override
public String getHookName() {
return "Citizens2(default)";
}
@Override
public String getHookVersion() {
return "2.2";
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new NCPHook() {
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, IViolationInfo info) {
return CitizensAPI.getNPCRegistry().isNPC(player);
}
@Override
public final String getHookVersion() {
return "2.0";
}
@Override
public final String getHookName() {
return "Citizens2(cncp)";
}
};
}
return (NCPHook) ncpHook;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -1,85 +1,85 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Exempting players by class names for some class.
* @author mc_dev
*
*/
public abstract class ClassExemptionHook extends AbstractHook implements ConfigurableHook{
protected final ExemptionManager man = new ExemptionManager();
protected final List<String> defaultClasses = new LinkedList<String>();
protected final LinkedHashSet<String> classes = new LinkedHashSet<String>();
protected boolean defaultEnabled = true;
protected boolean enabled = true;
protected final String configPrefix;
public ClassExemptionHook(String configPrefix){
this.configPrefix = configPrefix;
}
public void setClasses(final Collection<String> classes){
this.classes.clear();
this.classes.addAll(classes);
}
/**
* Check if a player is to be exempted and exempt for the check type.
* @param player
* @param clazz
* @param checkType
* @return If exempted.
*/
public boolean checkExempt(final Player player, final Class<?> clazz, final CheckType checkType){
if (!classes.contains(clazz.getSimpleName())) return false;
return man.addExemption(player, checkType);
}
/**
*
* @param player
* @param checkType
* @return If the player is still exempted.
*/
public boolean checkUnexempt(final Player player, final Class<?> clazz, final CheckType checkType){
if (!classes.contains(clazz.getSimpleName())) return false;
return man.removeExemption(player, checkType);
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", defaultEnabled);
ConfigUtil.readStringSetFromList(cfg, prefix + configPrefix + "exempt-names", classes, true, true, false);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", defaultEnabled);
defaults.set(prefix + configPrefix + "exempt-names", defaultClasses);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Exempting players by class names for some class.
* @author mc_dev
*
*/
public abstract class ClassExemptionHook extends AbstractHook implements ConfigurableHook{
protected final ExemptionManager man = new ExemptionManager();
protected final List<String> defaultClasses = new LinkedList<String>();
protected final LinkedHashSet<String> classes = new LinkedHashSet<String>();
protected boolean defaultEnabled = true;
protected boolean enabled = true;
protected final String configPrefix;
public ClassExemptionHook(String configPrefix){
this.configPrefix = configPrefix;
}
public void setClasses(final Collection<String> classes){
this.classes.clear();
this.classes.addAll(classes);
}
/**
* Check if a player is to be exempted and exempt for the check type.
* @param player
* @param clazz
* @param checkType
* @return If exempted.
*/
public boolean checkExempt(final Player player, final Class<?> clazz, final CheckType checkType){
if (!classes.contains(clazz.getSimpleName())) return false;
return man.addExemption(player, checkType);
}
/**
*
* @param player
* @param checkType
* @return If the player is still exempted.
*/
public boolean checkUnexempt(final Player player, final Class<?> clazz, final CheckType checkType){
if (!classes.contains(clazz.getSimpleName())) return false;
return man.removeExemption(player, checkType);
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", defaultEnabled);
ConfigUtil.readStringSetFromList(cfg, prefix + configPrefix + "exempt-names", classes, true, true, false);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", defaultEnabled);
defaults.set(prefix + configPrefix + "exempt-names", defaultClasses);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -1,32 +1,32 @@
package me.asofold.bpl.cncp.hooks.generic;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
/**
* A hook that is using configuration.
* @author mc_dev
*
*/
public interface ConfigurableHook {
/**
* Adjust internals to the given configuration.
* @param cfg
* @param prefix
*/
public void applyConfig(CompatConfig cfg, String prefix);
/**
* Update the given configuration with defaults where / if necessary (no blunt overwrite, it is a users config).
* @param cfg
* @param prefix
* @return If the configuration was changed.
*/
public boolean updateConfig(CompatConfig cfg, String prefix);
/**
* If the hook is enabled by configuration or not.
* @return
*/
public boolean isEnabled();
}
package me.asofold.bpl.cncp.hooks.generic;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
/**
* A hook that is using configuration.
* @author mc_dev
*
*/
public interface ConfigurableHook {
/**
* Adjust internals to the given configuration.
* @param cfg
* @param prefix
*/
public void applyConfig(CompatConfig cfg, String prefix);
/**
* Update the given configuration with defaults where / if necessary (no blunt overwrite, it is a users config).
* @param cfg
* @param prefix
* @return If the configuration was changed.
*/
public boolean updateConfig(CompatConfig cfg, String prefix);
/**
* If the hook is enabled by configuration or not.
* @return
*/
public boolean isEnabled();
}

View File

@ -1,224 +1,224 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
/**
* Auxiliary methods and data structure to handle simple sort of exemption. <br>
* NOTE: Not thread safe.
*
* @deprecated: Buggy / outdated concept - should not rely on nested stuff, use TickTask2 to unexempt timely if in doubt.
*
* @author mc_dev
*
*/
public class ExemptionManager{
public static enum Status{
EXEMPTED,
NOT_EXEMPTED,
NEEDS_EXEMPTION,
NEEDS_UNEXEMPTION,
}
public static class ExemptionInfo{
public static class CheckEntry{
public int skip = 0;
public int exempt = 0;
}
/** Counts per type, for players being exempted already, to prevent unexempting. */
public final Map<CheckType, CheckEntry> entries = new HashMap<CheckType, CheckEntry>();
/**
* If empty, it can get removed.
* @return
*/
public boolean isEmpty(){
return entries.isEmpty();
}
/**
*
* @param type
* @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type)
* @return EXEMPTED or NEEDS_EXEMPTION. The latter means the player has to be exempted.
*/
public Status increase(final CheckType type, final boolean isExempted){
final CheckEntry entry = entries.get(type);
if (entry == null){
final CheckEntry newEntry = new CheckEntry();
entries.put(type, newEntry);
if (isExempted){
newEntry.skip = 1;
return Status.EXEMPTED;
}
else{
newEntry.exempt = 1;
return Status.NEEDS_EXEMPTION;
}
}
if (entry.skip > 0){
if (isExempted){
entry.skip ++;
return Status.EXEMPTED;
}
else{
entry.exempt = entry.skip + 1;
entry.skip = 0;
return Status.NEEDS_EXEMPTION;
}
}
else{
// entry.exempt > 0
entry.exempt ++;
return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION;
}
}
/**
*
* @param type
* @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type)
* @return Status, if NEEDS_EXEMPTION the player has to be exempted. If NEEDS_UNEXEMPTION, the player has to be unexempted.
*/
public Status decrease(final CheckType type, final boolean isExempted){
final CheckEntry info = entries.get(type);
if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
if (info.skip > 0){
info.skip --;
if (info.skip == 0){
entries.remove(type);
return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
}
else if (isExempted) return Status.EXEMPTED;
else{
info.exempt = info.skip;
info.skip = 0;
return Status.NEEDS_EXEMPTION;
}
}
else{
info.exempt --;
if (info.exempt == 0){
entries.remove(type);
return isExempted ? Status.NEEDS_UNEXEMPTION : Status.NOT_EXEMPTED;
}
else{
return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION;
}
}
}
}
/** Exact player name -> ExemptionInfo */
protected final Map<String, ExemptionInfo> exemptions;
public ExemptionManager(){
this(30, 0.75f);
}
/**
*
* @param initialCapacity For the exemption HashMap.
* @param loadFactor For the exemption HashMap.
*/
public ExemptionManager(int initialCapacity, float loadFactor) {
exemptions = new HashMap<String, ExemptionManager.ExemptionInfo>(initialCapacity, loadFactor);
}
/**
* Add exemption count and exempt, if necessary.
* @param player
* @param type
* @return If the player was exempted already.
*/
public boolean addExemption(final Player player, final CheckType type){
final Status status = addExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type));
if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type);
// System.out.println("add: " + type.toString() + " -> " + status);
return status == Status.EXEMPTED;
}
/**
* Increment exemption count.
* @param name
* @return If exemption is needed (NEEDS_EXEMPTION).
*/
public Status addExemption(final String name, final CheckType type, boolean isExempted){
final ExemptionInfo info = exemptions.get(name);
final Status status;
if (info == null){
final ExemptionInfo newInfo = new ExemptionInfo();
status = newInfo.increase(type, isExempted);
exemptions.put(name, newInfo);
}
else{
status = info.increase(type, isExempted);
}
return status;
}
/**
* Decrement exemption count, exempt or unexempt if necessary.
* @param player
* @param type
* @return If the player is still exempted.
*/
public boolean removeExemption(final Player player, final CheckType type){
final Status status = removeExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type));
if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type);
else if (status == Status.NEEDS_UNEXEMPTION) NCPExemptionManager.unexempt(player, type);
// System.out.println("remove: " + type.toString() + " -> " + status);
return status == Status.EXEMPTED || status == Status.NEEDS_EXEMPTION;
}
/**
* Decrement exemption count.
* @param name
* @return Status, NEEDS_EXEMPTION and NEEDS_UNEXEMPTION make it necessary to call NCP API.
*/
public Status removeExemption(final String name, final CheckType type, boolean isExempted){
final ExemptionInfo info = exemptions.get(name);
if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
final Status status = info.decrease(type, isExempted);
if (info.isEmpty()) exemptions.remove(name);
return status;
}
/**
* Check if the player should be exempted right now according to stored info.
* @param name
* @param type
* @return
*/
public boolean shouldBeExempted(final String name, final CheckType type){
final ExemptionInfo info = exemptions.get(name);
if (info == null) return false;
return !info.isEmpty();
}
/**
* Hides the API access from listeners potentially.
* @param player
* @param checkType
*/
public void exempt(final Player player, final CheckType checkType){
NCPExemptionManager.exemptPermanently(player, checkType);
}
/**
* Hides the API access from listeners potentially.
* @param player
* @param checkType
*/
public void unexempt(final Player player, final CheckType checkType){
NCPExemptionManager.unexempt(player, checkType);
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
/**
* Auxiliary methods and data structure to handle simple sort of exemption. <br>
* NOTE: Not thread safe.
*
* @deprecated: Buggy / outdated concept - should not rely on nested stuff, use TickTask2 to unexempt timely if in doubt.
*
* @author mc_dev
*
*/
public class ExemptionManager{
public static enum Status{
EXEMPTED,
NOT_EXEMPTED,
NEEDS_EXEMPTION,
NEEDS_UNEXEMPTION,
}
public static class ExemptionInfo{
public static class CheckEntry{
public int skip = 0;
public int exempt = 0;
}
/** Counts per type, for players being exempted already, to prevent unexempting. */
public final Map<CheckType, CheckEntry> entries = new HashMap<CheckType, CheckEntry>();
/**
* If empty, it can get removed.
* @return
*/
public boolean isEmpty(){
return entries.isEmpty();
}
/**
*
* @param type
* @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type)
* @return EXEMPTED or NEEDS_EXEMPTION. The latter means the player has to be exempted.
*/
public Status increase(final CheckType type, final boolean isExempted){
final CheckEntry entry = entries.get(type);
if (entry == null){
final CheckEntry newEntry = new CheckEntry();
entries.put(type, newEntry);
if (isExempted){
newEntry.skip = 1;
return Status.EXEMPTED;
}
else{
newEntry.exempt = 1;
return Status.NEEDS_EXEMPTION;
}
}
if (entry.skip > 0){
if (isExempted){
entry.skip ++;
return Status.EXEMPTED;
}
else{
entry.exempt = entry.skip + 1;
entry.skip = 0;
return Status.NEEDS_EXEMPTION;
}
}
else{
// entry.exempt > 0
entry.exempt ++;
return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION;
}
}
/**
*
* @param type
* @param isExempted If the player is currently exempted, to be filled in with NCPHookManager.isExempted(player, type)
* @return Status, if NEEDS_EXEMPTION the player has to be exempted. If NEEDS_UNEXEMPTION, the player has to be unexempted.
*/
public Status decrease(final CheckType type, final boolean isExempted){
final CheckEntry info = entries.get(type);
if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
if (info.skip > 0){
info.skip --;
if (info.skip == 0){
entries.remove(type);
return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
}
else if (isExempted) return Status.EXEMPTED;
else{
info.exempt = info.skip;
info.skip = 0;
return Status.NEEDS_EXEMPTION;
}
}
else{
info.exempt --;
if (info.exempt == 0){
entries.remove(type);
return isExempted ? Status.NEEDS_UNEXEMPTION : Status.NOT_EXEMPTED;
}
else{
return isExempted ? Status.EXEMPTED : Status.NEEDS_EXEMPTION;
}
}
}
}
/** Exact player name -> ExemptionInfo */
protected final Map<String, ExemptionInfo> exemptions;
public ExemptionManager(){
this(30, 0.75f);
}
/**
*
* @param initialCapacity For the exemption HashMap.
* @param loadFactor For the exemption HashMap.
*/
public ExemptionManager(int initialCapacity, float loadFactor) {
exemptions = new HashMap<String, ExemptionManager.ExemptionInfo>(initialCapacity, loadFactor);
}
/**
* Add exemption count and exempt, if necessary.
* @param player
* @param type
* @return If the player was exempted already.
*/
public boolean addExemption(final Player player, final CheckType type){
final Status status = addExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type));
if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type);
// System.out.println("add: " + type.toString() + " -> " + status);
return status == Status.EXEMPTED;
}
/**
* Increment exemption count.
* @param name
* @return If exemption is needed (NEEDS_EXEMPTION).
*/
public Status addExemption(final String name, final CheckType type, boolean isExempted){
final ExemptionInfo info = exemptions.get(name);
final Status status;
if (info == null){
final ExemptionInfo newInfo = new ExemptionInfo();
status = newInfo.increase(type, isExempted);
exemptions.put(name, newInfo);
}
else{
status = info.increase(type, isExempted);
}
return status;
}
/**
* Decrement exemption count, exempt or unexempt if necessary.
* @param player
* @param type
* @return If the player is still exempted.
*/
public boolean removeExemption(final Player player, final CheckType type){
final Status status = removeExemption(player.getName(), type, NCPExemptionManager.isExempted(player, type));
if (status == Status.NEEDS_EXEMPTION) NCPExemptionManager.exemptPermanently(player, type);
else if (status == Status.NEEDS_UNEXEMPTION) NCPExemptionManager.unexempt(player, type);
// System.out.println("remove: " + type.toString() + " -> " + status);
return status == Status.EXEMPTED || status == Status.NEEDS_EXEMPTION;
}
/**
* Decrement exemption count.
* @param name
* @return Status, NEEDS_EXEMPTION and NEEDS_UNEXEMPTION make it necessary to call NCP API.
*/
public Status removeExemption(final String name, final CheckType type, boolean isExempted){
final ExemptionInfo info = exemptions.get(name);
if (info == null) return isExempted ? Status.EXEMPTED : Status.NOT_EXEMPTED;
final Status status = info.decrease(type, isExempted);
if (info.isEmpty()) exemptions.remove(name);
return status;
}
/**
* Check if the player should be exempted right now according to stored info.
* @param name
* @param type
* @return
*/
public boolean shouldBeExempted(final String name, final CheckType type){
final ExemptionInfo info = exemptions.get(name);
if (info == null) return false;
return !info.isEmpty();
}
/**
* Hides the API access from listeners potentially.
* @param player
* @param checkType
*/
public void exempt(final Player player, final CheckType checkType){
NCPExemptionManager.exemptPermanently(player, checkType);
}
/**
* Hides the API access from listeners potentially.
* @param player
* @param checkType
*/
public void unexempt(final Player player, final CheckType checkType){
NCPExemptionManager.unexempt(player, checkType);
}
}

View File

@ -1,64 +1,64 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Wrap block break events to exempt players from checks by comparison of event class names.
* @author mc_dev
*
*/
public class HookBlockBreak extends ClassExemptionHook implements Listener {
public HookBlockBreak() {
super("block-break.");
defaultClasses.addAll(Arrays.asList(new String[]{
// MachinaCraft
"ArtificialBlockBreakEvent",
// mcMMO
"FakeBlockBreakEvent",
// MagicSpells
"MagicSpellsBlockBreakEvent"
}));
}
@Override
public String getHookName() {
return "BlockBreak(default)";
}
@Override
public String getHookVersion() {
return "1.1";
}
@Override
public Listener[] getListeners() {
return new Listener[]{this};
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty()) enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onBlockBreakLowest(final BlockBreakEvent event){
checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK);
}
@EventHandler(priority = EventPriority.MONITOR)
final void onBlockBreakMonitor(final BlockBreakEvent event){
checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK);
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Wrap block break events to exempt players from checks by comparison of event class names.
* @author mc_dev
*
*/
public class HookBlockBreak extends ClassExemptionHook implements Listener {
public HookBlockBreak() {
super("block-break.");
defaultClasses.addAll(Arrays.asList(new String[]{
// MachinaCraft
"ArtificialBlockBreakEvent",
// mcMMO
"FakeBlockBreakEvent",
// MagicSpells
"MagicSpellsBlockBreakEvent"
}));
}
@Override
public String getHookName() {
return "BlockBreak(default)";
}
@Override
public String getHookVersion() {
return "1.1";
}
@Override
public Listener[] getListeners() {
return new Listener[]{this};
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty()) enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onBlockBreakLowest(final BlockBreakEvent event){
checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK);
}
@EventHandler(priority = EventPriority.MONITOR)
final void onBlockBreakMonitor(final BlockBreakEvent event){
checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKBREAK);
}
}

View File

@ -1,62 +1,62 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Wrap block place events to exempt players from checks by comparison of event class names.
* @author mc_dev
*
*/
public class HookBlockPlace extends ClassExemptionHook implements Listener{
public HookBlockPlace() {
super("block-place.");
defaultClasses.addAll(Arrays.asList(new String[]{
// MachinaCraft
"ArtificialBlockPlaceEvent",
// MagicSpells
"MagicSpellsBlockPlaceEvent"
}));
}
@Override
public String getHookName() {
return "BlockPlace(default)";
}
@Override
public String getHookVersion() {
return "1.0";
}
@Override
public Listener[] getListeners() {
return new Listener[]{this};
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty()) enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onBlockPlaceLowest(final BlockPlaceEvent event){
checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE);
}
@EventHandler(priority = EventPriority.MONITOR)
final void onBlockPlaceMonitor(final BlockPlaceEvent event){
checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE);
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
/**
* Wrap block place events to exempt players from checks by comparison of event class names.
* @author mc_dev
*
*/
public class HookBlockPlace extends ClassExemptionHook implements Listener{
public HookBlockPlace() {
super("block-place.");
defaultClasses.addAll(Arrays.asList(new String[]{
// MachinaCraft
"ArtificialBlockPlaceEvent",
// MagicSpells
"MagicSpellsBlockPlaceEvent"
}));
}
@Override
public String getHookName() {
return "BlockPlace(default)";
}
@Override
public String getHookVersion() {
return "1.0";
}
@Override
public Listener[] getListeners() {
return new Listener[]{this};
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty()) enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onBlockPlaceLowest(final BlockPlaceEvent event){
checkExempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE);
}
@EventHandler(priority = EventPriority.MONITOR)
final void onBlockPlaceMonitor(final BlockPlaceEvent event){
checkUnexempt(event.getPlayer(), event.getClass(), CheckType.BLOCKPLACE);
}
}

View File

@ -1,66 +1,66 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookEntityDamageByEntity extends ClassExemptionHook implements
Listener {
public HookEntityDamageByEntity() {
super("entity-damage-by-entity.");
defaultClasses.addAll(Arrays.asList(new String[] {
// CrackShot
"WeaponDamageEntityEvent",
// MagicSpells
"MagicSpellsEntityDamageByEntityEvent" }));
}
@Override
public String getHookName() {
return "EntityDamageByEntity(default)";
}
@Override
public String getHookVersion() {
return "0.0";
}
@Override
public Listener[] getListeners() {
return new Listener[] { this };
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty())
enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onDamageLowest(final EntityDamageByEntityEvent event) {
final Entity damager = event.getDamager();
if (damager instanceof Player) {
checkExempt((Player) damager, event.getClass(), CheckType.FIGHT);
}
}
@EventHandler(priority = EventPriority.MONITOR)
final void onDamageMonitor(final EntityDamageByEntityEvent event) {
final Entity damager = event.getDamager();
if (damager instanceof Player) {
checkUnexempt((Player) damager, event.getClass(), CheckType.FIGHT);
}
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookEntityDamageByEntity extends ClassExemptionHook implements
Listener {
public HookEntityDamageByEntity() {
super("entity-damage-by-entity.");
defaultClasses.addAll(Arrays.asList(new String[] {
// CrackShot
"WeaponDamageEntityEvent",
// MagicSpells
"MagicSpellsEntityDamageByEntityEvent" }));
}
@Override
public String getHookName() {
return "EntityDamageByEntity(default)";
}
@Override
public String getHookVersion() {
return "0.0";
}
@Override
public Listener[] getListeners() {
return new Listener[] { this };
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
if (classes.isEmpty())
enabled = false;
}
@EventHandler(priority = EventPriority.LOWEST)
final void onDamageLowest(final EntityDamageByEntityEvent event) {
final Entity damager = event.getDamager();
if (damager instanceof Player) {
checkExempt((Player) damager, event.getClass(), CheckType.FIGHT);
}
}
@EventHandler(priority = EventPriority.MONITOR)
final void onDamageMonitor(final EntityDamageByEntityEvent event) {
final Entity damager = event.getDamager();
if (damager instanceof Player) {
checkUnexempt((Player) damager, event.getClass(), CheckType.FIGHT);
}
}
}

View File

@ -1,171 +1,171 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.utilities.TickTask;
public class HookInstaBreak extends AbstractHook implements ConfigurableHook, Listener {
public static interface InstaExemption{
public void addExemptNext(CheckType[] types);
public Set<CheckType> getExemptNext();
}
public static class StackEntry{
public final CheckType[] checkTypes;
public final int tick;
public final Player player;
public boolean used = false;
public StackEntry(final Player player , final CheckType[] checkTypes){
this.player = player;
this.checkTypes = checkTypes;
tick = TickTask.getTick();
}
public boolean isOutdated(final int tick){
return tick != this.tick;
}
}
protected static InstaExemption runtime = null;
public static void addExemptNext(final CheckType[] types){
runtime.addExemptNext(types);
}
protected final ExemptionManager exMan = new ExemptionManager();
protected boolean enabled = true;
protected final List<StackEntry> stack = new LinkedList<StackEntry>();
@Override
public String getHookName() {
return "InstaBreak(default)";
}
@Override
public String getHookVersion() {
return "1.0";
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "insta-break.enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "insta-break.enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public CheckType[] getCheckTypes() {
return null;
}
@Override
public Listener[] getListeners() {
runtime = new InstaExemption() {
protected final Set<CheckType> types = new HashSet<CheckType>();
@Override
public final void addExemptNext(final CheckType[] types) {
for (int i = 0; i < types.length; i++){
this.types.add(types[i]);
}
}
@Override
public Set<CheckType> getExemptNext() {
return types;
}
};
return new Listener[]{this};
}
protected CheckType[] fetchTypes(){
final Set<CheckType> types = runtime.getExemptNext();
final CheckType[] a = new CheckType[types.size()];
if (!types.isEmpty()) types.toArray(a);
types.clear();
return a;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onBlockDamage(final BlockDamageEvent event){
checkStack();
if (!event.isCancelled() && event.getInstaBreak()){
stack.add(new StackEntry(event.getPlayer(), fetchTypes()));
}
else{
runtime.getExemptNext().clear();
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void onBlockBreakLowest(final BlockBreakEvent event){
checkStack();
if (!stack.isEmpty()){
final Player player = event.getPlayer();
final StackEntry entry = stack.get(stack.size() - 1);
if (player.equals(entry.player)) addExemption(entry);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onBlockBreakMONITOR(final BlockBreakEvent event){
if (!stack.isEmpty()){
final Player player = event.getPlayer();
final StackEntry entry = stack.get(stack.size() - 1);
if (player.equals(entry.player)) removeExemption(stack.remove(stack.size() - 1));
}
}
public void addExemption(final StackEntry entry){
entry.used = true;
for (int i = 0; i < entry.checkTypes.length; i++){
exMan.addExemption(entry.player, entry.checkTypes[i]);
}
}
public void removeExemption(final StackEntry entry){
if (!entry.used) return;
for (int i = 0; i < entry.checkTypes.length; i++){
exMan.removeExemption(entry.player, entry.checkTypes[i]);
}
}
public void checkStack(){
if (stack.isEmpty()) return;
Iterator<StackEntry> it = stack.iterator();
final int tick = TickTask.getTick();
while (it.hasNext()){
final StackEntry entry = it.next();
if (entry.isOutdated(tick)) it.remove();
if (entry.used) removeExemption(entry);
}
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.utilities.TickTask;
public class HookInstaBreak extends AbstractHook implements ConfigurableHook, Listener {
public static interface InstaExemption{
public void addExemptNext(CheckType[] types);
public Set<CheckType> getExemptNext();
}
public static class StackEntry{
public final CheckType[] checkTypes;
public final int tick;
public final Player player;
public boolean used = false;
public StackEntry(final Player player , final CheckType[] checkTypes){
this.player = player;
this.checkTypes = checkTypes;
tick = TickTask.getTick();
}
public boolean isOutdated(final int tick){
return tick != this.tick;
}
}
protected static InstaExemption runtime = null;
public static void addExemptNext(final CheckType[] types){
runtime.addExemptNext(types);
}
protected final ExemptionManager exMan = new ExemptionManager();
protected boolean enabled = true;
protected final List<StackEntry> stack = new LinkedList<StackEntry>();
@Override
public String getHookName() {
return "InstaBreak(default)";
}
@Override
public String getHookVersion() {
return "1.0";
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "insta-break.enabled", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "insta-break.enabled", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public CheckType[] getCheckTypes() {
return null;
}
@Override
public Listener[] getListeners() {
runtime = new InstaExemption() {
protected final Set<CheckType> types = new HashSet<CheckType>();
@Override
public final void addExemptNext(final CheckType[] types) {
for (int i = 0; i < types.length; i++){
this.types.add(types[i]);
}
}
@Override
public Set<CheckType> getExemptNext() {
return types;
}
};
return new Listener[]{this};
}
protected CheckType[] fetchTypes(){
final Set<CheckType> types = runtime.getExemptNext();
final CheckType[] a = new CheckType[types.size()];
if (!types.isEmpty()) types.toArray(a);
types.clear();
return a;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onBlockDamage(final BlockDamageEvent event){
checkStack();
if (!event.isCancelled() && event.getInstaBreak()){
stack.add(new StackEntry(event.getPlayer(), fetchTypes()));
}
else{
runtime.getExemptNext().clear();
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
public void onBlockBreakLowest(final BlockBreakEvent event){
checkStack();
if (!stack.isEmpty()){
final Player player = event.getPlayer();
final StackEntry entry = stack.get(stack.size() - 1);
if (player.equals(entry.player)) addExemption(entry);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void onBlockBreakMONITOR(final BlockBreakEvent event){
if (!stack.isEmpty()){
final Player player = event.getPlayer();
final StackEntry entry = stack.get(stack.size() - 1);
if (player.equals(entry.player)) removeExemption(stack.remove(stack.size() - 1));
}
}
public void addExemption(final StackEntry entry){
entry.used = true;
for (int i = 0; i < entry.checkTypes.length; i++){
exMan.addExemption(entry.player, entry.checkTypes[i]);
}
}
public void removeExemption(final StackEntry entry){
if (!entry.used) return;
for (int i = 0; i < entry.checkTypes.length; i++){
exMan.removeExemption(entry.player, entry.checkTypes[i]);
}
}
public void checkStack(){
if (stack.isEmpty()) return;
Iterator<StackEntry> it = stack.iterator();
final int tick = TickTask.getTick();
while (it.hasNext()){
final StackEntry entry = it.next();
if (entry.isOutdated(tick)) it.remove();
if (entry.used) removeExemption(entry);
}
}
}

View File

@ -1,121 +1,121 @@
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public final class HookPlayerClass extends AbstractHook implements ConfigurableHook {
private static final boolean defaultEnabled = false;
protected final Set<String> classNames = new HashSet<String>();
protected boolean exemptAll = true;
protected boolean checkSuperClass = true;
protected Object ncpHook = null;
protected boolean enabled = defaultEnabled;
/**
* Normal class name.
*/
protected Set<String> playerClassNames = new HashSet<String>();
public HookPlayerClass(){
// TODO: Might need cleanup.
this.playerClassNames.addAll(Arrays.asList(new String[]{"CraftPlayer", "SpoutCraftPlayer", "SpoutPlayer", "SpoutClientPlayer", "SpoutPlayerSnapshot"}));
}
@Override
public final String getHookName() {
return "PlayerClass(default)";
}
@Override
public final String getHookVersion() {
return "2.3";
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new NCPHook() {
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) {
if (exemptAll && !playerClassNames.contains(player.getClass().getSimpleName())) return true;
else {
if (classNames.isEmpty()) return false;
final Class<?> clazz = player.getClass();
final String name = clazz.getSimpleName();
if (classNames.contains(name)) return true;
else if (checkSuperClass){
while (true){
final Class<?> superClass = clazz.getSuperclass();
if (superClass == null) return false;
else{
final String superName = superClass.getSimpleName();
if (superName.equals("Object")) return false;
else if (classNames.contains(superName)){
return true;
}
}
}
}
}
return false; // ECLIPSE
}
@Override
public String getHookVersion() {
return "3.1";
}
@Override
public String getHookName() {
return "PlayerClass(cncp)";
}
};
}
return (NCPHook) ncpHook;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "player-class.enabled", defaultEnabled);
ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.exempt-names", classNames, true, true, false);
exemptAll = cfg.getBoolean(prefix + "player-class.exempt-all", true);
ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.class-names", playerClassNames, true, true, false);
checkSuperClass = cfg.getBoolean(prefix + "player-class.super-class", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "player-class.enabled", defaultEnabled);
defaults.set(prefix + "player-class.exempt-names", new LinkedList<String>());
defaults.set(prefix + "player-class.exempt-all", true);
defaults.set(prefix + "player-class.class-names", new LinkedList<String>(playerClassNames));
defaults.set(prefix + "player-class.super-class", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}
package me.asofold.bpl.cncp.hooks.generic;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public final class HookPlayerClass extends AbstractHook implements ConfigurableHook {
private static final boolean defaultEnabled = false;
protected final Set<String> classNames = new HashSet<String>();
protected boolean exemptAll = true;
protected boolean checkSuperClass = true;
protected Object ncpHook = null;
protected boolean enabled = defaultEnabled;
/**
* Normal class name.
*/
protected Set<String> playerClassNames = new HashSet<String>();
public HookPlayerClass(){
// TODO: Might need cleanup.
this.playerClassNames.addAll(Arrays.asList(new String[]{"CraftPlayer", "SpoutCraftPlayer", "SpoutPlayer", "SpoutClientPlayer", "SpoutPlayerSnapshot"}));
}
@Override
public final String getHookName() {
return "PlayerClass(default)";
}
@Override
public final String getHookVersion() {
return "2.3";
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new NCPHook() {
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) {
if (exemptAll && !playerClassNames.contains(player.getClass().getSimpleName())) return true;
else {
if (classNames.isEmpty()) return false;
final Class<?> clazz = player.getClass();
final String name = clazz.getSimpleName();
if (classNames.contains(name)) return true;
else if (checkSuperClass){
while (true){
final Class<?> superClass = clazz.getSuperclass();
if (superClass == null) return false;
else{
final String superName = superClass.getSimpleName();
if (superName.equals("Object")) return false;
else if (classNames.contains(superName)){
return true;
}
}
}
}
}
return false; // ECLIPSE
}
@Override
public String getHookVersion() {
return "3.1";
}
@Override
public String getHookName() {
return "PlayerClass(cncp)";
}
};
}
return (NCPHook) ncpHook;
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "player-class.enabled", defaultEnabled);
ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.exempt-names", classNames, true, true, false);
exemptAll = cfg.getBoolean(prefix + "player-class.exempt-all", true);
ConfigUtil.readStringSetFromList(cfg, prefix + "player-class.class-names", playerClassNames, true, true, false);
checkSuperClass = cfg.getBoolean(prefix + "player-class.super-class", true);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "player-class.enabled", defaultEnabled);
defaults.set(prefix + "player-class.exempt-names", new LinkedList<String>());
defaults.set(prefix + "player-class.exempt-all", true);
defaults.set(prefix + "player-class.class-names", new LinkedList<String>(playerClassNames));
defaults.set(prefix + "player-class.super-class", true);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -1,106 +1,106 @@
package me.asofold.bpl.cncp.hooks.generic;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookSetSpeed extends AbstractHook implements Listener, ConfigurableHook{
private static final float defaultFlySpeed = 0.1f;
private static final float defaultWalkSpeed = 0.2f;
protected float flySpeed = defaultFlySpeed;
protected float walkSpeed = defaultWalkSpeed;
protected boolean enabled = false;
// private String allowFlightPerm = "cncp.allow-flight";
public HookSetSpeed() throws SecurityException, NoSuchMethodException{
Player.class.getDeclaredMethod("setFlySpeed", float.class);
}
public void init(){
for (final Player player : Bukkit.getOnlinePlayers()){
setSpeed(player);
}
}
@Override
public String getHookName() {
return "SetSpeed(default)";
}
@Override
public String getHookVersion() {
return "2.2";
}
@Override
public CheckType[] getCheckTypes() {
return new CheckType[0];
}
@Override
public Listener[] getListeners() {
try{
// Initialize here, at the end of enable.
init();
}
catch (Throwable t){}
return new Listener[]{this} ;
}
public final void setSpeed(final Player player){
// if (allowFlightPerm.equals("") || player.hasPermission(allowFlightPerm)) player.setAllowFlight(true);
player.setWalkSpeed(walkSpeed);
player.setFlySpeed(flySpeed);
}
@EventHandler(priority=EventPriority.LOWEST)
public final void onPlayerJoin(final PlayerJoinEvent event){
setSpeed(event.getPlayer());
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "set-speed.enabled", false);
flySpeed = cfg.getDouble(prefix + "set-speed.fly-speed", (double) defaultFlySpeed).floatValue();
walkSpeed = cfg.getDouble(prefix + "set-speed.walk-speed", (double) defaultWalkSpeed).floatValue();
// allowFlightPerm = cfg.getString(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "set-speed.enabled", false);
defaults.set(prefix + "set-speed.fly-speed", defaultFlySpeed);
defaults.set(prefix + "set-speed.walk-speed", defaultWalkSpeed);
// cfg.set(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
// public String getAllowFlightPerm() {
// return allowFlightPerm;
// }
// public void setAllowFlightPerm(String allowFlightPerm) {
// this.allowFlightPerm = allowFlightPerm;
// }
}
package me.asofold.bpl.cncp.hooks.generic;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookSetSpeed extends AbstractHook implements Listener, ConfigurableHook{
private static final float defaultFlySpeed = 0.1f;
private static final float defaultWalkSpeed = 0.2f;
protected float flySpeed = defaultFlySpeed;
protected float walkSpeed = defaultWalkSpeed;
protected boolean enabled = false;
// private String allowFlightPerm = "cncp.allow-flight";
public HookSetSpeed() throws SecurityException, NoSuchMethodException{
Player.class.getDeclaredMethod("setFlySpeed", float.class);
}
public void init(){
for (final Player player : Bukkit.getOnlinePlayers()){
setSpeed(player);
}
}
@Override
public String getHookName() {
return "SetSpeed(default)";
}
@Override
public String getHookVersion() {
return "2.2";
}
@Override
public CheckType[] getCheckTypes() {
return new CheckType[0];
}
@Override
public Listener[] getListeners() {
try{
// Initialize here, at the end of enable.
init();
}
catch (Throwable t){}
return new Listener[]{this} ;
}
public final void setSpeed(final Player player){
// if (allowFlightPerm.equals("") || player.hasPermission(allowFlightPerm)) player.setAllowFlight(true);
player.setWalkSpeed(walkSpeed);
player.setFlySpeed(flySpeed);
}
@EventHandler(priority=EventPriority.LOWEST)
public final void onPlayerJoin(final PlayerJoinEvent event){
setSpeed(event.getPlayer());
}
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + "set-speed.enabled", false);
flySpeed = cfg.getDouble(prefix + "set-speed.fly-speed", (double) defaultFlySpeed).floatValue();
walkSpeed = cfg.getDouble(prefix + "set-speed.walk-speed", (double) defaultWalkSpeed).floatValue();
// allowFlightPerm = cfg.getString(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + "set-speed.enabled", false);
defaults.set(prefix + "set-speed.fly-speed", defaultFlySpeed);
defaults.set(prefix + "set-speed.walk-speed", defaultWalkSpeed);
// cfg.set(prefix + "set-speed.allow-flight-permission", ref.allowFlightPerm);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
// public String getAllowFlightPerm() {
// return allowFlightPerm;
// }
// public void setAllowFlightPerm(String allowFlightPerm) {
// this.allowFlightPerm = allowFlightPerm;
// }
}

View File

@ -1,121 +1,121 @@
package me.asofold.bpl.cncp.hooks.magicspells;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractConfigurableHook;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookMagicSpells extends AbstractConfigurableHook implements Listener{
protected final Map<String, CheckType[]> spellMap = new HashMap<String, CheckType[]>();
public HookMagicSpells(){
super("MagicSpells(default)", "1.0", "magicspells.");
assertPluginPresent("MagicSpells");
}
@Override
public Listener[] getListeners() {
return new Listener[]{
this
};
}
// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
// public void onSpellCast(final SpellCastEvent event){
// if (event.getSpellCastState() != SpellCastState.NORMAL) return;
// exempt(event.getCaster(), event.getSpell());
// }
//
// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
// public void onSpellCasted(final SpellCastedEvent event){
// unexempt(event.getCaster(), event.getSpell());
// }
//
// private void exempt(final Player player, final Spell spell) {
// final CheckType[] types = getCheckTypes(spell);
// if (types == null) return;
// for (final CheckType type : types){
// NCPExemptionManager.exemptPermanently(player, type);
// // Safety fall-back:
// // TODO: Might interfere with "slow" effects of spells ? [might add config for this.]
// TickTask2.addUnexemptions(player, types);
// }
// }
//
// private void unexempt(final Player player, final Spell spell) {
// final CheckType[] types = getCheckTypes(spell);
// if (types == null) return;
// for (final CheckType type : types){
// NCPExemptionManager.unexempt(player, type);
// }
// }
//
// protected CheckType[] getCheckTypes(final Spell spell){
// return spellMap.get(spell.getName());
// }
/* (non-Javadoc)
* @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#applyConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String)
*/
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
prefix += this.configPrefix;
List<String> keys = cfg.getStringKeys(prefix + "exempt-spells");
for (String key : keys){
String fullKey = ConfigUtil.bestPath(cfg, prefix + "exempt-spells." + key);
String types = cfg.getString(fullKey);
if (types == null) continue;
String[] split = types.split(",");
Set<CheckType> checkTypes = new HashSet<CheckType>();
for (String input : split){
input = input.trim().toUpperCase().replace('-', '_').replace(' ', '_').replace('.', '_');
CheckType type = null;
try{
type = CheckType.valueOf(input);
}
catch(Throwable t){
}
if (type == null){
Bukkit.getLogger().warning("[cncp] HookMagicSpells: Bad check type at " + fullKey + ": " + input);
}
else checkTypes.add(type);
}
if (checkTypes.isEmpty()){
Bukkit.getLogger().warning("[cncp] HookMagicSpells: No CheckType entries at: " + fullKey);
}
else{
CheckType[] a = new CheckType[checkTypes.size()];
checkTypes.toArray(a);
spellMap.put(key, a);
}
}
}
/* (non-Javadoc)
* @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#updateConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String)
*/
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
super.updateConfig(cfg, prefix);
CompatConfig defaults = CompatConfigFactory.getConfig(null);
prefix += this.configPrefix;
// TODO: Write default section.
defaults.set(prefix + "NOTE", "MagicSpells support is experimental, only instant spells can be added here.");
defaults.set(prefix + "exempt-spells.NameOfExampleSpell", "COMBINED_MUNCHHAUSEN, UNKNOWN, BLOCKPLACE_NOSWING");
return ConfigUtil.forceDefaults(defaults, cfg);
}
}
package me.asofold.bpl.cncp.hooks.magicspells;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractConfigurableHook;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import fr.neatmonster.nocheatplus.checks.CheckType;
public class HookMagicSpells extends AbstractConfigurableHook implements Listener{
protected final Map<String, CheckType[]> spellMap = new HashMap<String, CheckType[]>();
public HookMagicSpells(){
super("MagicSpells(default)", "1.0", "magicspells.");
assertPluginPresent("MagicSpells");
}
@Override
public Listener[] getListeners() {
return new Listener[]{
this
};
}
// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
// public void onSpellCast(final SpellCastEvent event){
// if (event.getSpellCastState() != SpellCastState.NORMAL) return;
// exempt(event.getCaster(), event.getSpell());
// }
//
// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
// public void onSpellCasted(final SpellCastedEvent event){
// unexempt(event.getCaster(), event.getSpell());
// }
//
// private void exempt(final Player player, final Spell spell) {
// final CheckType[] types = getCheckTypes(spell);
// if (types == null) return;
// for (final CheckType type : types){
// NCPExemptionManager.exemptPermanently(player, type);
// // Safety fall-back:
// // TODO: Might interfere with "slow" effects of spells ? [might add config for this.]
// TickTask2.addUnexemptions(player, types);
// }
// }
//
// private void unexempt(final Player player, final Spell spell) {
// final CheckType[] types = getCheckTypes(spell);
// if (types == null) return;
// for (final CheckType type : types){
// NCPExemptionManager.unexempt(player, type);
// }
// }
//
// protected CheckType[] getCheckTypes(final Spell spell){
// return spellMap.get(spell.getName());
// }
/* (non-Javadoc)
* @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#applyConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String)
*/
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
super.applyConfig(cfg, prefix);
prefix += this.configPrefix;
List<String> keys = cfg.getStringKeys(prefix + "exempt-spells");
for (String key : keys){
String fullKey = ConfigUtil.bestPath(cfg, prefix + "exempt-spells." + key);
String types = cfg.getString(fullKey);
if (types == null) continue;
String[] split = types.split(",");
Set<CheckType> checkTypes = new HashSet<CheckType>();
for (String input : split){
input = input.trim().toUpperCase().replace('-', '_').replace(' ', '_').replace('.', '_');
CheckType type = null;
try{
type = CheckType.valueOf(input);
}
catch(Throwable t){
}
if (type == null){
Bukkit.getLogger().warning("[cncp] HookMagicSpells: Bad check type at " + fullKey + ": " + input);
}
else checkTypes.add(type);
}
if (checkTypes.isEmpty()){
Bukkit.getLogger().warning("[cncp] HookMagicSpells: No CheckType entries at: " + fullKey);
}
else{
CheckType[] a = new CheckType[checkTypes.size()];
checkTypes.toArray(a);
spellMap.put(key, a);
}
}
}
/* (non-Javadoc)
* @see me.asofold.bpl.cncp.hooks.AbstractConfigurableHook#updateConfig(me.asofold.bpl.cncp.config.compatlayer.CompatConfig, java.lang.String)
*/
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
super.updateConfig(cfg, prefix);
CompatConfig defaults = CompatConfigFactory.getConfig(null);
prefix += this.configPrefix;
// TODO: Write default section.
defaults.set(prefix + "NOTE", "MagicSpells support is experimental, only instant spells can be added here.");
defaults.set(prefix + "exempt-spells.NameOfExampleSpell", "COMBINED_MUNCHHAUSEN, UNKNOWN, BLOCKPLACE_NOSWING");
return ConfigUtil.forceDefaults(defaults, cfg);
}
}

View File

@ -1,256 +1,256 @@
package me.asofold.bpl.cncp.hooks.mcmmo;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
import fr.neatmonster.nocheatplus.players.DataManager;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolProps;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolType;
import me.asofold.bpl.cncp.CompatNoCheatPlus;
import me.asofold.bpl.cncp.hooks.generic.ExemptionManager;
import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak;
import me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO.HookFacade;
import me.asofold.bpl.cncp.utils.ActionFrequency;
import me.asofold.bpl.cncp.utils.TickTask2;
@SuppressWarnings("deprecation")
public class HookFacadeImpl implements HookFacade, NCPHook {
protected final ExemptionManager exMan = new ExemptionManager();
/** Normal click per block skills. */
protected final CheckType[] exemptBreakNormal = new CheckType[]{
CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_FREQUENCY,
CheckType.BLOCKBREAK_NOSWING,
CheckType.BLOCKBREAK_WRONGBLOCK, // Not optimal but ok.
};
protected final CheckType[] exemptBreakMany = new CheckType[]{
CheckType.BLOCKBREAK, CheckType.COMBINED_IMPROBABLE,
};
/** Fighting damage of effects such as bleeding or area (potentially). */
protected final CheckType[] exemptFightEffect = new CheckType[]{
CheckType.FIGHT_SPEED, CheckType.FIGHT_DIRECTION,
CheckType.FIGHT_ANGLE, CheckType.FIGHT_NOSWING,
CheckType.FIGHT_REACH, CheckType.COMBINED_IMPROBABLE,
};
// Presets for after failure exemption.
protected final Map<CheckType, Integer> cancelChecksBlockBreak = new HashMap<CheckType, Integer>();
// protected final Map<CheckType, Integer> cancelChecksBlockDamage = new HashMap<CheckType, Integer>();
// protected final Map<CheckType, Integer> cancelChecksDamage = new HashMap<CheckType, Integer>();
protected boolean useInstaBreakHook;
protected int clicksPerSecond;
protected String cancel = null;
protected long cancelTicks = 0;
protected final Map<CheckType, Integer> cancelChecks = new HashMap<CheckType, Integer>();
/**
* Last block breaking time
*/
protected final Map<String, ActionFrequency> lastBreak = new HashMap<String, ActionFrequency>(50);
/** Counter for nested events to cancel break counting. */
protected int breakCancel = 0;
protected int lastBreakAddCount = 0;
protected long lastBreakCleanup = 0;
public HookFacadeImpl(boolean useInstaBreakHook, int clicksPerSecond){
this.useInstaBreakHook = useInstaBreakHook;
this.clicksPerSecond = clicksPerSecond;
cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_NOSWING, 1);
cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_FASTBREAK, 1);
//
// cancelChecksBlockDamage.put(CheckType.BLOCKBREAK_FASTBREAK, 1);
//
// cancelChecksDamage.put(CheckType.FIGHT_ANGLE, 1);
// cancelChecksDamage.put(CheckType.FIGHT_SPEED, 1);
}
@Override
public String getHookName() {
return "mcMMO(cncp)";
}
@Override
public String getHookVersion() {
return "2.3";
}
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) {
// System.out.println(player.getName() + " -> " + checkType + "---------------------------");
// Somewhat generic canceling mechanism (within the same tick).
// Might later fail, if block break event gets scheduled after block damage having set insta break, instead of letting them follow directly.
if (cancel == null){
return false;
}
final String name = player.getName();
if (cancel.equals(name)){
if (player.getTicksLived() != cancelTicks){
cancel = null;
}
else{
final Integer n = cancelChecks.get(checkType);
if (n == null){
return false;
}
else if (n > 0){
if (n == 1) cancelChecks.remove(checkType);
else cancelChecks.put(checkType, n - 1);
}
return true;
}
}
return false;
}
private final void setPlayer(final Player player, Map<CheckType, Integer> cancelChecks){
cancel = player.getName();
cancelTicks = player.getTicksLived();
this.cancelChecks.clear();
this.cancelChecks.putAll(cancelChecks);
}
public ToolProps getToolProps(final ItemStack stack){
if (stack == null) return BlockProperties.noTool;
else return BlockProperties.getToolProps(stack);
}
public void addExemption(final Player player, final CheckType[] types){
for (final CheckType type : types){
exMan.addExemption(player, type);
TickTask2.addUnexemptions(player, types);
}
}
public void removeExemption(final Player player, final CheckType[] types){
for (final CheckType type : types){
exMan.removeExemption(player, type);
}
}
@Override
public final void damageLowest(final Player player) {
// System.out.println("damage lowest");
// setPlayer(player, cancelChecksDamage);
addExemption(player, exemptFightEffect);
}
@Override
public final void blockDamageLowest(final Player player) {
// System.out.println("block damage lowest");
// setPlayer(player, cancelChecksBlockDamage);
if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany);
else addExemption(player, exemptBreakNormal);
}
@Override
public final boolean blockBreakLowest(final Player player) {
// System.out.println("block break lowest");
final boolean isAxe = getToolProps(player.getItemInHand()).toolType == ToolType.AXE;
if (breakCancel > 0){
breakCancel ++;
return true;
}
final String name = player.getName();
ActionFrequency freq = lastBreak.get(name);
final long now = System.currentTimeMillis();
if (freq == null){
freq = new ActionFrequency(3, 333);
freq.add(now, 1f);
lastBreak.put(name, freq);
lastBreakAddCount ++;
if (lastBreakAddCount > 100){
lastBreakAddCount = 0;
cleanupLastBreaks();
}
}
else if (!isAxe){
freq.add(now, 1f);
if (freq.score(1f) > (float) clicksPerSecond){
breakCancel ++;
return true;
}
}
addExemption(player, exemptBreakNormal);
if (useInstaBreakHook){
HookInstaBreak.addExemptNext(exemptBreakNormal);
TickTask2.addUnexemptions(player, exemptBreakNormal);
}
else if (!isAxe){
setPlayer(player, cancelChecksBlockBreak);
Bukkit.getScheduler().scheduleSyncDelayedTask(CompatNoCheatPlus.getInstance(), new Runnable() {
@Override
public void run() {
DataManager.removeData(player.getName(), CheckType.BLOCKBREAK_FASTBREAK);
}
});
}
return false;
}
protected void cleanupLastBreaks() {
final long ts = System.currentTimeMillis();
if (ts - lastBreakCleanup < 30000 && ts > lastBreakCleanup) return;
lastBreakCleanup = ts;
final List<String> rem = new LinkedList<String>();
if (ts >= lastBreakCleanup){
for (final Entry<String, ActionFrequency> entry : lastBreak.entrySet()){
if (entry.getValue().score(1f) == 0f) rem.add(entry.getKey());
}
}
else{
rem.addAll(lastBreak.keySet());
}
for (final String key :rem){
lastBreak.remove(key);
}
}
@Override
public void damageMonitor(Player player) {
// System.out.println("damage monitor");
removeExemption(player, exemptFightEffect);
}
@Override
public void blockDamageMonitor(Player player) {
// System.out.println("block damage monitor");
if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany);
else removeExemption(player, exemptBreakNormal);
}
@Override
public void blockBreakMontitor(Player player) {
if (breakCancel > 0){
breakCancel --;
return;
}
// System.out.println("block break monitor");
removeExemption(player, exemptBreakNormal);
}
}
package me.asofold.bpl.cncp.hooks.mcmmo;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.checks.access.IViolationInfo;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
import fr.neatmonster.nocheatplus.players.DataManager;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolProps;
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties.ToolType;
import me.asofold.bpl.cncp.CompatNoCheatPlus;
import me.asofold.bpl.cncp.hooks.generic.ExemptionManager;
import me.asofold.bpl.cncp.hooks.generic.HookInstaBreak;
import me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO.HookFacade;
import me.asofold.bpl.cncp.utils.ActionFrequency;
import me.asofold.bpl.cncp.utils.TickTask2;
@SuppressWarnings("deprecation")
public class HookFacadeImpl implements HookFacade, NCPHook {
protected final ExemptionManager exMan = new ExemptionManager();
/** Normal click per block skills. */
protected final CheckType[] exemptBreakNormal = new CheckType[]{
CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_FREQUENCY,
CheckType.BLOCKBREAK_NOSWING,
CheckType.BLOCKBREAK_WRONGBLOCK, // Not optimal but ok.
};
protected final CheckType[] exemptBreakMany = new CheckType[]{
CheckType.BLOCKBREAK, CheckType.COMBINED_IMPROBABLE,
};
/** Fighting damage of effects such as bleeding or area (potentially). */
protected final CheckType[] exemptFightEffect = new CheckType[]{
CheckType.FIGHT_SPEED, CheckType.FIGHT_DIRECTION,
CheckType.FIGHT_ANGLE, CheckType.FIGHT_NOSWING,
CheckType.FIGHT_REACH, CheckType.COMBINED_IMPROBABLE,
};
// Presets for after failure exemption.
protected final Map<CheckType, Integer> cancelChecksBlockBreak = new HashMap<CheckType, Integer>();
// protected final Map<CheckType, Integer> cancelChecksBlockDamage = new HashMap<CheckType, Integer>();
// protected final Map<CheckType, Integer> cancelChecksDamage = new HashMap<CheckType, Integer>();
protected boolean useInstaBreakHook;
protected int clicksPerSecond;
protected String cancel = null;
protected long cancelTicks = 0;
protected final Map<CheckType, Integer> cancelChecks = new HashMap<CheckType, Integer>();
/**
* Last block breaking time
*/
protected final Map<String, ActionFrequency> lastBreak = new HashMap<String, ActionFrequency>(50);
/** Counter for nested events to cancel break counting. */
protected int breakCancel = 0;
protected int lastBreakAddCount = 0;
protected long lastBreakCleanup = 0;
public HookFacadeImpl(boolean useInstaBreakHook, int clicksPerSecond){
this.useInstaBreakHook = useInstaBreakHook;
this.clicksPerSecond = clicksPerSecond;
cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_NOSWING, 1);
cancelChecksBlockBreak.put(CheckType.BLOCKBREAK_FASTBREAK, 1);
//
// cancelChecksBlockDamage.put(CheckType.BLOCKBREAK_FASTBREAK, 1);
//
// cancelChecksDamage.put(CheckType.FIGHT_ANGLE, 1);
// cancelChecksDamage.put(CheckType.FIGHT_SPEED, 1);
}
@Override
public String getHookName() {
return "mcMMO(cncp)";
}
@Override
public String getHookVersion() {
return "2.3";
}
@Override
public final boolean onCheckFailure(final CheckType checkType, final Player player, final IViolationInfo info) {
// System.out.println(player.getName() + " -> " + checkType + "---------------------------");
// Somewhat generic canceling mechanism (within the same tick).
// Might later fail, if block break event gets scheduled after block damage having set insta break, instead of letting them follow directly.
if (cancel == null){
return false;
}
final String name = player.getName();
if (cancel.equals(name)){
if (player.getTicksLived() != cancelTicks){
cancel = null;
}
else{
final Integer n = cancelChecks.get(checkType);
if (n == null){
return false;
}
else if (n > 0){
if (n == 1) cancelChecks.remove(checkType);
else cancelChecks.put(checkType, n - 1);
}
return true;
}
}
return false;
}
private final void setPlayer(final Player player, Map<CheckType, Integer> cancelChecks){
cancel = player.getName();
cancelTicks = player.getTicksLived();
this.cancelChecks.clear();
this.cancelChecks.putAll(cancelChecks);
}
public ToolProps getToolProps(final ItemStack stack){
if (stack == null) return BlockProperties.noTool;
else return BlockProperties.getToolProps(stack);
}
public void addExemption(final Player player, final CheckType[] types){
for (final CheckType type : types){
exMan.addExemption(player, type);
TickTask2.addUnexemptions(player, types);
}
}
public void removeExemption(final Player player, final CheckType[] types){
for (final CheckType type : types){
exMan.removeExemption(player, type);
}
}
@Override
public final void damageLowest(final Player player) {
// System.out.println("damage lowest");
// setPlayer(player, cancelChecksDamage);
addExemption(player, exemptFightEffect);
}
@Override
public final void blockDamageLowest(final Player player) {
// System.out.println("block damage lowest");
// setPlayer(player, cancelChecksBlockDamage);
if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany);
else addExemption(player, exemptBreakNormal);
}
@Override
public final boolean blockBreakLowest(final Player player) {
// System.out.println("block break lowest");
final boolean isAxe = getToolProps(player.getItemInHand()).toolType == ToolType.AXE;
if (breakCancel > 0){
breakCancel ++;
return true;
}
final String name = player.getName();
ActionFrequency freq = lastBreak.get(name);
final long now = System.currentTimeMillis();
if (freq == null){
freq = new ActionFrequency(3, 333);
freq.add(now, 1f);
lastBreak.put(name, freq);
lastBreakAddCount ++;
if (lastBreakAddCount > 100){
lastBreakAddCount = 0;
cleanupLastBreaks();
}
}
else if (!isAxe){
freq.add(now, 1f);
if (freq.score(1f) > (float) clicksPerSecond){
breakCancel ++;
return true;
}
}
addExemption(player, exemptBreakNormal);
if (useInstaBreakHook){
HookInstaBreak.addExemptNext(exemptBreakNormal);
TickTask2.addUnexemptions(player, exemptBreakNormal);
}
else if (!isAxe){
setPlayer(player, cancelChecksBlockBreak);
Bukkit.getScheduler().scheduleSyncDelayedTask(CompatNoCheatPlus.getInstance(), new Runnable() {
@Override
public void run() {
DataManager.removeData(player.getName(), CheckType.BLOCKBREAK_FASTBREAK);
}
});
}
return false;
}
protected void cleanupLastBreaks() {
final long ts = System.currentTimeMillis();
if (ts - lastBreakCleanup < 30000 && ts > lastBreakCleanup) return;
lastBreakCleanup = ts;
final List<String> rem = new LinkedList<String>();
if (ts >= lastBreakCleanup){
for (final Entry<String, ActionFrequency> entry : lastBreak.entrySet()){
if (entry.getValue().score(1f) == 0f) rem.add(entry.getKey());
}
}
else{
rem.addAll(lastBreak.keySet());
}
for (final String key :rem){
lastBreak.remove(key);
}
}
@Override
public void damageMonitor(Player player) {
// System.out.println("damage monitor");
removeExemption(player, exemptFightEffect);
}
@Override
public void blockDamageMonitor(Player player) {
// System.out.println("block damage monitor");
if (getToolProps(player.getItemInHand()).toolType == ToolType.AXE) addExemption(player, exemptBreakMany);
else removeExemption(player, exemptBreakNormal);
}
@Override
public void blockBreakMontitor(Player player) {
if (breakCancel > 0){
breakCancel --;
return;
}
// System.out.println("block break monitor");
removeExemption(player, exemptBreakNormal);
}
}

View File

@ -1,178 +1,178 @@
package me.asofold.bpl.cncp.hooks.mcmmo;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
import me.asofold.bpl.cncp.utils.PluginGetter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.events.fake.FakeBlockDamageEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public final class HookmcMMO extends AbstractHook implements Listener, ConfigurableHook {
/**
* To let the listener access this.
* @author mc_dev
*
*/
public static interface HookFacade{
public void damageLowest(Player player);
public void damageMonitor(Player player);
public void blockDamageLowest(Player player);
public void blockDamageMonitor(Player player);
/**
* If to cancel the event.
* @param player
* @return
*/
public boolean blockBreakLowest(Player player);
public void blockBreakMontitor(Player player);
}
protected HookFacade ncpHook = null;
protected boolean enabled = true;
protected String configPrefix = "mcmmo.";
protected boolean useInstaBreakHook = true;
public HookmcMMO(){
assertPluginPresent("mcMMO");
}
protected final PluginGetter<mcMMO> fetch = new PluginGetter<mcMMO>("mcMMO");
protected int blocksPerSecond = 30;
@Override
public String getHookName() {
return "mcMMO(default)";
}
@Override
public String getHookVersion() {
return "2.1";
}
@Override
public CheckType[] getCheckTypes() {
return new CheckType[]{
CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_NOSWING, // old ones
// CheckType.BLOCKBREAK_DIRECTION, CheckType.BLOCKBREAK_FREQUENCY,
// CheckType.BLOCKBREAK_WRONGBLOCK, CheckType.BLOCKBREAK_REACH,
//
// CheckType.FIGHT_ANGLE, CheckType.FIGHT_SPEED, // old ones
//
// CheckType.FIGHT_DIRECTION, CheckType.FIGHT_NOSWING,
// CheckType.FIGHT_REACH,
};
}
@Override
public Listener[] getListeners() {
fetch.fetchPlugin();
return new Listener[]{this, fetch};
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new HookFacadeImpl(useInstaBreakHook, blocksPerSecond);
}
return (NCPHook) ncpHook;
}
///////////////////////////
// Damage (fight)
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onDamageLowest(final FakeEntityDamageByEntityEvent event){
final Entity entity = event.getDamager();
if (entity instanceof Player)
ncpHook.damageLowest((Player) entity);
}
@EventHandler(priority=EventPriority.MONITOR)
final void onDamageMonitor(final FakeEntityDamageByEntityEvent event){
final Entity entity = event.getDamager();
if (entity instanceof Player)
ncpHook.damageMonitor((Player) entity);
}
///////////////////////////
// Block damage
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockDamageLowest(final FakeBlockDamageEvent event){
ncpHook.blockDamageLowest(event.getPlayer());
}
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockDamageMonitor(final FakeBlockDamageEvent event){
ncpHook.blockDamageMonitor(event.getPlayer());
}
///////////////////////////
// Block break
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockBreakLowest(final FakeBlockBreakEvent event){
if (ncpHook.blockBreakLowest(event.getPlayer())){
event.setCancelled(true);
// System.out.println("Cancelled for frequency.");
}
}
@EventHandler(priority=EventPriority.MONITOR)
final void onBlockBreakLMonitor(final FakeBlockBreakEvent event){
ncpHook.blockBreakMontitor(event.getPlayer());
}
/////////////////////////////////
// Config
/////////////////////////////////
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
useInstaBreakHook = cfg.getBoolean(prefix + configPrefix + "use-insta-break-hook", true);
blocksPerSecond = cfg.getInt(prefix + configPrefix + "clickspersecond", 20);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
defaults.set(prefix + configPrefix + "use-insta-break-hook", true);
defaults.set(prefix + configPrefix + "clickspersecond", 20);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}
package me.asofold.bpl.cncp.hooks.mcmmo;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfig;
import me.asofold.bpl.cncp.config.compatlayer.CompatConfigFactory;
import me.asofold.bpl.cncp.config.compatlayer.ConfigUtil;
import me.asofold.bpl.cncp.hooks.AbstractHook;
import me.asofold.bpl.cncp.hooks.generic.ConfigurableHook;
import me.asofold.bpl.cncp.utils.PluginGetter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import com.gmail.nossr50.events.fake.FakeBlockDamageEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPHook;
public final class HookmcMMO extends AbstractHook implements Listener, ConfigurableHook {
/**
* To let the listener access this.
* @author mc_dev
*
*/
public static interface HookFacade{
public void damageLowest(Player player);
public void damageMonitor(Player player);
public void blockDamageLowest(Player player);
public void blockDamageMonitor(Player player);
/**
* If to cancel the event.
* @param player
* @return
*/
public boolean blockBreakLowest(Player player);
public void blockBreakMontitor(Player player);
}
protected HookFacade ncpHook = null;
protected boolean enabled = true;
protected String configPrefix = "mcmmo.";
protected boolean useInstaBreakHook = true;
public HookmcMMO(){
assertPluginPresent("mcMMO");
}
protected final PluginGetter<mcMMO> fetch = new PluginGetter<mcMMO>("mcMMO");
protected int blocksPerSecond = 30;
@Override
public String getHookName() {
return "mcMMO(default)";
}
@Override
public String getHookVersion() {
return "2.1";
}
@Override
public CheckType[] getCheckTypes() {
return new CheckType[]{
CheckType.BLOCKBREAK_FASTBREAK, CheckType.BLOCKBREAK_NOSWING, // old ones
// CheckType.BLOCKBREAK_DIRECTION, CheckType.BLOCKBREAK_FREQUENCY,
// CheckType.BLOCKBREAK_WRONGBLOCK, CheckType.BLOCKBREAK_REACH,
//
// CheckType.FIGHT_ANGLE, CheckType.FIGHT_SPEED, // old ones
//
// CheckType.FIGHT_DIRECTION, CheckType.FIGHT_NOSWING,
// CheckType.FIGHT_REACH,
};
}
@Override
public Listener[] getListeners() {
fetch.fetchPlugin();
return new Listener[]{this, fetch};
}
@Override
public NCPHook getNCPHook() {
if (ncpHook == null){
ncpHook = new HookFacadeImpl(useInstaBreakHook, blocksPerSecond);
}
return (NCPHook) ncpHook;
}
///////////////////////////
// Damage (fight)
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onDamageLowest(final FakeEntityDamageByEntityEvent event){
final Entity entity = event.getDamager();
if (entity instanceof Player)
ncpHook.damageLowest((Player) entity);
}
@EventHandler(priority=EventPriority.MONITOR)
final void onDamageMonitor(final FakeEntityDamageByEntityEvent event){
final Entity entity = event.getDamager();
if (entity instanceof Player)
ncpHook.damageMonitor((Player) entity);
}
///////////////////////////
// Block damage
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockDamageLowest(final FakeBlockDamageEvent event){
ncpHook.blockDamageLowest(event.getPlayer());
}
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockDamageMonitor(final FakeBlockDamageEvent event){
ncpHook.blockDamageMonitor(event.getPlayer());
}
///////////////////////////
// Block break
//////////////////////////
@EventHandler(priority=EventPriority.LOWEST)
final void onBlockBreakLowest(final FakeBlockBreakEvent event){
if (ncpHook.blockBreakLowest(event.getPlayer())){
event.setCancelled(true);
// System.out.println("Cancelled for frequency.");
}
}
@EventHandler(priority=EventPriority.MONITOR)
final void onBlockBreakLMonitor(final FakeBlockBreakEvent event){
ncpHook.blockBreakMontitor(event.getPlayer());
}
/////////////////////////////////
// Config
/////////////////////////////////
@Override
public void applyConfig(CompatConfig cfg, String prefix) {
enabled = cfg.getBoolean(prefix + configPrefix + "enabled", true);
useInstaBreakHook = cfg.getBoolean(prefix + configPrefix + "use-insta-break-hook", true);
blocksPerSecond = cfg.getInt(prefix + configPrefix + "clickspersecond", 20);
}
@Override
public boolean updateConfig(CompatConfig cfg, String prefix) {
CompatConfig defaults = CompatConfigFactory.getConfig(null);
defaults.set(prefix + configPrefix + "enabled", true);
defaults.set(prefix + configPrefix + "use-insta-break-hook", true);
defaults.set(prefix + configPrefix + "clickspersecond", 20);
return ConfigUtil.forceDefaults(defaults, cfg);
}
@Override
public boolean isEnabled() {
return enabled;
}
}

View File

@ -1,290 +1,290 @@
package me.asofold.bpl.cncp.utils;
/**
* Keep track of frequency of some action,
* put weights into buckets, which represent intervals of time. <br>
* (Taken from NoCheatPlus.)
* @author mc_dev
*
*/
public class ActionFrequency {
/** Reference time for the transition from the first to the second bucket. */
private long time = 0;
/**
* Time of last update (add). Should be the "time of the last event" for the
* usual case.
*/
private long lastUpdate = 0;
private final boolean noAutoReset;
/**
* Buckets to fill weights in, each represents an interval of durBucket duration,
* index 0 is the latest, highest index is the oldest.
* Weights will get filled into the next buckets with time passed.
*/
private final float[] buckets;
/** Duration in milliseconds that one bucket covers. */
private final long durBucket;
/**
* This constructor will set noAutoReset to false, optimized for short term
* accounting.
*
* @param nBuckets
* @param durBucket
*/
public ActionFrequency(final int nBuckets, final long durBucket) {
this(nBuckets, durBucket, false);
}
/**
*
* @param nBuckets
* @param durBucket
* @param noAutoReset
* Set to true, to prevent auto-resetting with
* "time ran backwards". Setting this to true is recommended if
* larger time frames are monitored, to prevent data loss.
*/
public ActionFrequency(final int nBuckets, final long durBucket, final boolean noAutoReset) {
this.buckets = new float[nBuckets];
this.durBucket = durBucket;
this.noAutoReset = noAutoReset;
}
/**
* Update and add (updates reference and update time).
* @param now
* @param amount
*/
public final void add(final long now, final float amount) {
update(now);
buckets[0] += amount;
}
/**
* Unchecked addition of amount to the first bucket.
* @param amount
*/
public final void add(final float amount) {
buckets[0] += amount;
}
/**
* Update without adding, also updates reference and update time. Detects
* time running backwards.
*
* @param now
*/
public final void update(final long now) {
final long diff = now - time;
if (now < lastUpdate) {
// Time ran backwards.
if (noAutoReset) {
// Only update time and lastUpdate.
time = lastUpdate = now;
} else {
// Clear all.
clear(now);
return;
}
}
else if (diff >= durBucket * buckets.length) {
// Clear (beyond range).
clear(now);
return;
}
else if (diff < durBucket) {
// No changes (first bucket).
}
else {
final int shift = (int) ((float) diff / (float) durBucket);
// Update buckets.
for (int i = 0; i < buckets.length - shift; i++) {
buckets[buckets.length - (i + 1)] = buckets[buckets.length - (i + 1 + shift)];
}
for (int i = 0; i < shift; i++) {
buckets[i] = 0;
}
// Set time according to bucket duration (!).
time += durBucket * shift;
}
// Ensure lastUpdate is set.
lastUpdate = now;
}
/**
* Clear all counts, reset reference and update time.
* @param now
*/
public final void clear(final long now) {
for (int i = 0; i < buckets.length; i++) {
buckets[i] = 0f;
}
time = lastUpdate = now;
}
/**
* @deprecated Use instead: score(float).
* @param factor
* @return
*/
public final float getScore(final float factor) {
return score(factor);
}
/**
* @deprecated Use instead: score(float).
* @param factor
* @return
*/
public final float getScore(final int bucket) {
return bucketScore(bucket);
}
/**
* Get a weighted sum score, weight for bucket i: w(i) = factor^i.
* @param factor
* @return
*/
public final float score(final float factor) {
return sliceScore(0, buckets.length, factor);
}
/**
* Get score of a certain bucket. At own risk.
* @param bucket
* @return
*/
public final float bucketScore(final int bucket) {
return buckets[bucket];
}
/**
* Get score of first end buckets, with factor.
* @param end Number of buckets including start. The end is not included.
* @param factor
* @return
*/
public final float leadingScore(final int end, float factor) {
return sliceScore(0, end, factor);
}
/**
* Get score from start on, with factor.
* @param start This is included.
* @param factor
* @return
*/
public final float trailingScore(final int start, float factor) {
return sliceScore(start, buckets.length, factor);
}
/**
* Get score from start on, until before end, with factor.
* @param start This is included.
* @param end This is not included.
* @param factor
* @return
*/
public final float sliceScore(final int start, final int end, float factor) {
float score = buckets[start];
float cf = factor;
for (int i = start + 1; i < end; i++) {
score += buckets[i] * cf;
cf *= factor;
}
return score;
}
/**
* Set the value for a buckt.
* @param n
* @param value
*/
public final void setBucket(final int n, final float value) {
buckets[n] = value;
}
/**
* Set the reference time and last update time.
* @param time
*/
public final void setTime(final long time) {
this.time = time;
this.lastUpdate = time;
}
/**
* Get the reference time for the transition from the first to the second bucket.
* @return
*/
public final long lastAccess() { // TODO: Should rename this.
return time;
}
/**
* Get the last time when update was called (adding).
* @return
*/
public final long lastUpdate() {
return lastUpdate;
}
/**
* Get the number of buckets.
* @return
*/
public final int numberOfBuckets() {
return buckets.length;
}
/**
* Get the duration of a bucket in milliseconds.
* @return
*/
public final long bucketDuration() {
return durBucket;
}
/**
* Serialize to a String line.
* @return
*/
public final String toLine() {
// TODO: Backwards-compatible lastUpdate ?
final StringBuilder buffer = new StringBuilder(50);
buffer.append(buckets.length + ","+durBucket+","+time);
for (int i = 0; i < buckets.length; i++) {
buffer.append("," + buckets[i]);
}
return buffer.toString();
}
/**
* Deserialize from a string.
* @param line
* @return
*/
public static ActionFrequency fromLine(final String line) {
// TODO: Backwards-compatible lastUpdate ?
String[] split = line.split(",");
if (split.length < 3) throw new RuntimeException("Bad argument length."); // TODO
final int n = Integer.parseInt(split[0]);
final long durBucket = Long.parseLong(split[1]);
final long time = Long.parseLong(split[2]);
final float[] buckets = new float[split.length -3];
if (split.length - 3 != buckets.length) throw new RuntimeException("Bad argument length."); // TODO
for (int i = 3; i < split.length; i ++) {
buckets[i - 3] = Float.parseFloat(split[i]);
}
ActionFrequency freq = new ActionFrequency(n, durBucket);
freq.setTime(time);
for (int i = 0; i < buckets.length; i ++) {
freq.setBucket(i, buckets[i]);
}
return freq;
}
}
package me.asofold.bpl.cncp.utils;
/**
* Keep track of frequency of some action,
* put weights into buckets, which represent intervals of time. <br>
* (Taken from NoCheatPlus.)
* @author mc_dev
*
*/
public class ActionFrequency {
/** Reference time for the transition from the first to the second bucket. */
private long time = 0;
/**
* Time of last update (add). Should be the "time of the last event" for the
* usual case.
*/
private long lastUpdate = 0;
private final boolean noAutoReset;
/**
* Buckets to fill weights in, each represents an interval of durBucket duration,
* index 0 is the latest, highest index is the oldest.
* Weights will get filled into the next buckets with time passed.
*/
private final float[] buckets;
/** Duration in milliseconds that one bucket covers. */
private final long durBucket;
/**
* This constructor will set noAutoReset to false, optimized for short term
* accounting.
*
* @param nBuckets
* @param durBucket
*/
public ActionFrequency(final int nBuckets, final long durBucket) {
this(nBuckets, durBucket, false);
}
/**
*
* @param nBuckets
* @param durBucket
* @param noAutoReset
* Set to true, to prevent auto-resetting with
* "time ran backwards". Setting this to true is recommended if
* larger time frames are monitored, to prevent data loss.
*/
public ActionFrequency(final int nBuckets, final long durBucket, final boolean noAutoReset) {
this.buckets = new float[nBuckets];
this.durBucket = durBucket;
this.noAutoReset = noAutoReset;
}
/**
* Update and add (updates reference and update time).
* @param now
* @param amount
*/
public final void add(final long now, final float amount) {
update(now);
buckets[0] += amount;
}
/**
* Unchecked addition of amount to the first bucket.
* @param amount
*/
public final void add(final float amount) {
buckets[0] += amount;
}
/**
* Update without adding, also updates reference and update time. Detects
* time running backwards.
*
* @param now
*/
public final void update(final long now) {
final long diff = now - time;
if (now < lastUpdate) {
// Time ran backwards.
if (noAutoReset) {
// Only update time and lastUpdate.
time = lastUpdate = now;
} else {
// Clear all.
clear(now);
return;
}
}
else if (diff >= durBucket * buckets.length) {
// Clear (beyond range).
clear(now);
return;
}
else if (diff < durBucket) {
// No changes (first bucket).
}
else {
final int shift = (int) ((float) diff / (float) durBucket);
// Update buckets.
for (int i = 0; i < buckets.length - shift; i++) {
buckets[buckets.length - (i + 1)] = buckets[buckets.length - (i + 1 + shift)];
}
for (int i = 0; i < shift; i++) {
buckets[i] = 0;
}
// Set time according to bucket duration (!).
time += durBucket * shift;
}
// Ensure lastUpdate is set.
lastUpdate = now;
}
/**
* Clear all counts, reset reference and update time.
* @param now
*/
public final void clear(final long now) {
for (int i = 0; i < buckets.length; i++) {
buckets[i] = 0f;
}
time = lastUpdate = now;
}
/**
* @deprecated Use instead: score(float).
* @param factor
* @return
*/
public final float getScore(final float factor) {
return score(factor);
}
/**
* @deprecated Use instead: score(float).
* @param factor
* @return
*/
public final float getScore(final int bucket) {
return bucketScore(bucket);
}
/**
* Get a weighted sum score, weight for bucket i: w(i) = factor^i.
* @param factor
* @return
*/
public final float score(final float factor) {
return sliceScore(0, buckets.length, factor);
}
/**
* Get score of a certain bucket. At own risk.
* @param bucket
* @return
*/
public final float bucketScore(final int bucket) {
return buckets[bucket];
}
/**
* Get score of first end buckets, with factor.
* @param end Number of buckets including start. The end is not included.
* @param factor
* @return
*/
public final float leadingScore(final int end, float factor) {
return sliceScore(0, end, factor);
}
/**
* Get score from start on, with factor.
* @param start This is included.
* @param factor
* @return
*/
public final float trailingScore(final int start, float factor) {
return sliceScore(start, buckets.length, factor);
}
/**
* Get score from start on, until before end, with factor.
* @param start This is included.
* @param end This is not included.
* @param factor
* @return
*/
public final float sliceScore(final int start, final int end, float factor) {
float score = buckets[start];
float cf = factor;
for (int i = start + 1; i < end; i++) {
score += buckets[i] * cf;
cf *= factor;
}
return score;
}
/**
* Set the value for a buckt.
* @param n
* @param value
*/
public final void setBucket(final int n, final float value) {
buckets[n] = value;
}
/**
* Set the reference time and last update time.
* @param time
*/
public final void setTime(final long time) {
this.time = time;
this.lastUpdate = time;
}
/**
* Get the reference time for the transition from the first to the second bucket.
* @return
*/
public final long lastAccess() { // TODO: Should rename this.
return time;
}
/**
* Get the last time when update was called (adding).
* @return
*/
public final long lastUpdate() {
return lastUpdate;
}
/**
* Get the number of buckets.
* @return
*/
public final int numberOfBuckets() {
return buckets.length;
}
/**
* Get the duration of a bucket in milliseconds.
* @return
*/
public final long bucketDuration() {
return durBucket;
}
/**
* Serialize to a String line.
* @return
*/
public final String toLine() {
// TODO: Backwards-compatible lastUpdate ?
final StringBuilder buffer = new StringBuilder(50);
buffer.append(buckets.length + ","+durBucket+","+time);
for (int i = 0; i < buckets.length; i++) {
buffer.append("," + buckets[i]);
}
return buffer.toString();
}
/**
* Deserialize from a string.
* @param line
* @return
*/
public static ActionFrequency fromLine(final String line) {
// TODO: Backwards-compatible lastUpdate ?
String[] split = line.split(",");
if (split.length < 3) throw new RuntimeException("Bad argument length."); // TODO
final int n = Integer.parseInt(split[0]);
final long durBucket = Long.parseLong(split[1]);
final long time = Long.parseLong(split[2]);
final float[] buckets = new float[split.length -3];
if (split.length - 3 != buckets.length) throw new RuntimeException("Bad argument length."); // TODO
for (int i = 3; i < split.length; i ++) {
buckets[i - 3] = Float.parseFloat(split[i]);
}
ActionFrequency freq = new ActionFrequency(n, durBucket);
freq.setTime(time);
for (int i = 0; i < buckets.length; i ++) {
freq.setBucket(i, buckets[i]);
}
return freq;
}
}

View File

@ -1,50 +1,50 @@
package me.asofold.bpl.cncp.utils;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
/**
* Simple plugin fetching.
* @author mc_dev
*
* @param <T>
*/
public final class PluginGetter<T extends Plugin> implements Listener{
private T plugin = null;
private final String pluginName;
public PluginGetter(final String pluginName){
this.pluginName = pluginName;
fetchPlugin();
}
/**
* Fetch from Bukkit and set , might set to null, though.
*/
@SuppressWarnings("unchecked")
public final void fetchPlugin() {
final Plugin ref = Bukkit.getPluginManager().getPlugin(pluginName);
plugin = (T) ref;
}
@SuppressWarnings("unchecked")
final void onPluginEnable(final PluginEnableEvent event){
final Plugin ref = event.getPlugin();
if (plugin.getName().equals(pluginName)) plugin = (T) ref;
}
/**
* For convenience with chaining: getX = new PluginGetter<X>("X").registerEvents(this);
* @param other
* @return
*/
public final PluginGetter<T> registerEvents(final Plugin other){
Bukkit.getPluginManager().registerEvents(this, plugin);
return this;
}
public final T getPlugin(){
return plugin;
}
}
package me.asofold.bpl.cncp.utils;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
/**
* Simple plugin fetching.
* @author mc_dev
*
* @param <T>
*/
public final class PluginGetter<T extends Plugin> implements Listener{
private T plugin = null;
private final String pluginName;
public PluginGetter(final String pluginName){
this.pluginName = pluginName;
fetchPlugin();
}
/**
* Fetch from Bukkit and set , might set to null, though.
*/
@SuppressWarnings("unchecked")
public final void fetchPlugin() {
final Plugin ref = Bukkit.getPluginManager().getPlugin(pluginName);
plugin = (T) ref;
}
@SuppressWarnings("unchecked")
final void onPluginEnable(final PluginEnableEvent event){
final Plugin ref = event.getPlugin();
if (plugin.getName().equals(pluginName)) plugin = (T) ref;
}
/**
* For convenience with chaining: getX = new PluginGetter<X>("X").registerEvents(this);
* @param other
* @return
*/
public final PluginGetter<T> registerEvents(final Plugin other){
Bukkit.getPluginManager().registerEvents(this, plugin);
return this;
}
public final T getPlugin(){
return plugin;
}
}

View File

@ -1,48 +1,48 @@
package me.asofold.bpl.cncp.utils;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
public class TickTask2 implements Runnable {
protected static Map<CheckType, Set<Player>> exemptions = new LinkedHashMap<CheckType, Set<Player>>(40);
/**
* Quick fix, meant for sync access (!).
* @param player
* @param checkTypes
*/
public static void addUnexemptions(final Player player, final CheckType[] checkTypes){
for (int i = 0; i < checkTypes.length; i ++){
final CheckType type = checkTypes[i];
Set<Player> set = exemptions.get(type);
if (set == null){
set = new HashSet<Player>();
exemptions.put(type, set);
}
set.add(player);
}
}
@Override
public void run() {
for (final Entry<CheckType, Set<Player>> entry : exemptions.entrySet()){
final Set<Player> set = entry.getValue();
final CheckType type = entry.getKey();
for (final Player player : set){
NCPExemptionManager.unexempt(player, type);
}
}
exemptions.clear();
}
}
package me.asofold.bpl.cncp.utils;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager;
public class TickTask2 implements Runnable {
protected static Map<CheckType, Set<Player>> exemptions = new LinkedHashMap<CheckType, Set<Player>>(40);
/**
* Quick fix, meant for sync access (!).
* @param player
* @param checkTypes
*/
public static void addUnexemptions(final Player player, final CheckType[] checkTypes){
for (int i = 0; i < checkTypes.length; i ++){
final CheckType type = checkTypes[i];
Set<Player> set = exemptions.get(type);
if (set == null){
set = new HashSet<Player>();
exemptions.put(type, set);
}
set.add(player);
}
}
@Override
public void run() {
for (final Entry<CheckType, Set<Player>> entry : exemptions.entrySet()){
final Set<Player> set = entry.getValue();
final CheckType type = entry.getKey();
for (final Player player : set){
NCPExemptionManager.unexempt(player, type);
}
}
exemptions.clear();
}
}

View File

@ -1,16 +1,16 @@
package me.asofold.bpl.cncp.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
public class Utils {
public static final String toString(final Throwable t) {
final Writer buf = new StringWriter(500);
final PrintWriter writer = new PrintWriter(buf);
t.printStackTrace(writer);
return buf.toString();
}
}
package me.asofold.bpl.cncp.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
public class Utils {
public static final String toString(final Throwable t) {
final Writer buf = new StringWriter(500);
final PrintWriter writer = new PrintWriter(buf);
t.printStackTrace(writer);
return buf.toString();
}
}