Compare commits

..

19 commits

Author SHA1 Message Date
d46adfd957
Fix custom charts
Probably
2021-02-21 02:15:10 +01:00
12a8ccf3ce
Use bStats for metrics and remove Piwik integration
#4
2021-02-21 01:39:51 +01:00
dcd3ff31db
Fix WorldEdit integration stopping edits
It's been only more than a year, it's fine
2021-02-21 00:04:56 +01:00
e4548069dc
Update dependencies 2020-07-27 16:24:42 +02:00
3f9c2b99f9
Version update 2019-09-21 16:28:47 +02:00
6d5f42b2a5
Added ReflectionStorage (mostly version-independent)
(Started on 2019.08.29.)
This means it supports 1.14.4
It automatically falls back to the previous storage if the newer version is not found
2019-09-21 16:14:58 +02:00
14bdf0ebe0
Updated WorldEdit and WorldGuard to 7.0.0
It doesn't work without them atm because it tries to load a class from them
2019-08-28 23:29:40 +02:00
24ed3393d3
Giving 30 seconds max for the thread
The plugin will wait 30 seconds and if the thread is still alive then it interrupts the thread which should instantly end the loop.
Also other fixes
Also notifying all threads that could wait on the queue, though it should be the only 1 BS thread
2018-10-04 00:34:00 +02:00
cd7b7a550d
Might have fixed the stop delay
The theory is the following: multiple BS threads were created, one for each chunk, which caused long locks. If this isn't the case, I don't know what is.
#2
2018-08-31 17:08:06 +02:00
b84ecf8545
Added conversion in DB 2018-06-30 16:28:32 +02:00
ecaecd4136
Added name to UUID conversion 2018-06-27 21:59:12 +02:00
362d1d823c
Small fixes, ready to go 2018-06-27 17:53:04 +02:00
b8d21657ce
Merge remote-tracking branch 'remotes/origin/spigot-1.9'
# Conflicts:
#	pom.xml
#	src/main/java/de/jaschastarke/minecraft/limitedcreative/FeatureMetrics.java
#	src/main/java/de/jaschastarke/minecraft/limitedcreative/blockstate/worldedit/LCEditSession_LogBlock.java
#	src/main/java/de/jaschastarke/minecraft/limitedcreative/limits/PlayerListener.java
2018-06-27 13:42:29 +02:00
d7e4eafc4d
Fixed thread stop & metrics fix
The thread will be restarted automatically after an error
2018-06-27 00:14:09 +02:00
f2af77b9b7
Resolved compile errors, LB removed
LogBlock support removed
2018-06-26 21:28:36 +02:00
pickernickel
8c1240cc24 Use UUID instead of player name. 2016-05-23 22:42:52 -05:00
pickernickel
05d37326e0 Circumvented some deprecated API usage. 2016-05-22 04:35:52 -05:00
pickernickel
b2e154be45 Slime block compatibility. 2016-05-18 03:34:19 -05:00
Jascha Starke
8cfc3b7f01 Spigot 1.9 Update 2016-03-02 22:47:46 +01:00
31 changed files with 1691 additions and 1420 deletions

View file

@ -17,4 +17,12 @@ Dependencies for optional integrations
* [Multiverse-Core](http://dev.bukkit.org/bukkit-plugins/multiverse-core/) * [Multiverse-Core](http://dev.bukkit.org/bukkit-plugins/multiverse-core/)
* [Vault](http://dev.bukkit.org/bukkit-plugins/vault/) * [Vault](http://dev.bukkit.org/bukkit-plugins/vault/)
* [Multiworld](http://dev.bukkit.org/bukkit-plugins/multiworld-v-2-0/) * [Multiworld](http://dev.bukkit.org/bukkit-plugins/multiworld-v-2-0/)
* [LogBlock](http://dev.bukkit.org/bukkit-plugins/logblock/) * [LogBlock](http://dev.bukkit.org/bukkit-plugins/logblock/)
Building
--------
Download and install xAuth and Multiworld into the local `repo` repository with a command like so:
```bash
mvn install:install-file -Dfile=xAuth-2.0.26.jar -Dpackaging=jar -DlocalRepositoryPath=repo -DgroupId=de.luricos.bukkit -DartifactId=xAuth -Dversion=2.0.26
```

568
pom.xml
View file

@ -1,267 +1,303 @@
<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"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<modelVersion>4.0.0</modelVersion> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>de.jaschastarke</groupId> <modelVersion>4.0.0</modelVersion>
<artifactId>LimitedCreative</artifactId> <groupId>de.jaschastarke</groupId>
<name>LimitedCreative</name> <artifactId>LimitedCreative</artifactId>
<version>2.3-SNAPSHOT</version> <name>LimitedCreative</name>
<url>https://github.com/possi/LimitedCreative</url> <version>2.5</version>
<url>https://github.com/possi/LimitedCreative</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <properties>
<plib.version>1.4-SNAPSHOT</plib.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<bukkit.version>1.8.3-R0.1-SNAPSHOT</bukkit.version> <plib.version>1.4-SNAPSHOT</plib.version>
</properties> <bukkit.version>1.12.2-R0.1-SNAPSHOT</bukkit.version>
</properties>
<scm>
<connection>scm:git:git://github.com/possi/LimitedCreative.git</connection> <scm>
<developerConnection>scm:git:git@github.com:possi/LimitedCreative.git</developerConnection> <connection>scm:git:git://github.com/possi/LimitedCreative.git</connection>
<url>https://github.com/possi/LimitedCreative/tree/plib</url> <developerConnection>scm:git:git@github.com:possi/LimitedCreative.git</developerConnection>
</scm> <url>https://github.com/possi/LimitedCreative/tree/plib</url>
<distributionManagement> </scm>
<repository> <distributionManagement>
<id>de-jas-repo</id> <repository>
<url>scp://repo@ja-s.de/var/customers/webs/repo/mvn</url> <id>de-jas-repo</id>
</repository> <url>scp://repo@ja-s.de/var/customers/webs/repo/mvn</url>
</distributionManagement> </repository>
<ciManagement> </distributionManagement>
<system>jenkins</system> <ciManagement>
<url>http://ci.ja-s.de:8080/</url> <system>jenkins</system>
</ciManagement> <url>http://ci.ja-s.de:8080/</url>
<issueManagement> </ciManagement>
<system>BukkitDev</system> <issueManagement>
<url>http://dev.bukkit.org/server-mods/limited-creative/tickets/</url> <system>BukkitDev</system>
</issueManagement> <url>http://dev.bukkit.org/server-mods/limited-creative/tickets/</url>
</issueManagement>
<repositories>
<!-- Possible public Maven Repository, containing LimitedCreative builds and other dependencies without own rep. <repositories>
like AuthMe, etc. <!-- Possible public Maven Repository, containing LimitedCreative builds and other dependencies without own rep.
Supports http only --> like AuthMe, etc.
<repository> Supports http only -->
<id>de-jas-rep</id> <!-- <repository> - offline
<url>http://repo.ja-s.de/mvn</url> <id>de-jas-rep</id>
</repository> <url>http://repo.ja-s.de/mvn</url>
</repository> -->
<!-- (Craft-)Bukkit repository --> <!-- Local repository for plugins without a repo -->
<repository> <repository>
<id>spigot-repo</id> <id>localRepo</id>
<url>http://repo.bukkit.org/content/groups/public</url> <url>file://${project.basedir}/repo</url>
</repository> </repository>
<!-- Official WorldGuard and WorldEdit repository -->
<repository> <!-- Official (Craft-)Bukkit repository -->
<id>sk89q-mvn2</id> <repository>
<url>http://mvn2.sk89q.com/repo</url> <id>spigot-repo</id>
</repository> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
<!-- Official Multiverse repository --> </repository>
<repository> <!-- Official WorldGuard and WorldEdit repository -->
<id>onarandombox</id> <repository>
<url>http://repo.onarandombox.com/content/groups/public</url> <id>sk89q-mvn2</id>
</repository> <url>https://maven.enginehub.org/repo/</url>
<!-- Official xAuth repository; it is no good! we keep our own dep-files of it - -> </repository>
<repository> <!-- Official Multiverse repository -->
<id>luricos.de-repo</id> <repository>
<url>http://repo.luricos.de/bukkit-plugins/</url> <id>onarandombox</id>
</repository><!- - --> <url>http://repo.onarandombox.com/content/groups/public</url>
<!-- Official LogBlock repository --> </repository>
<repository> <!-- Official xAuth repository; it is no good! we keep our own dep-files of it - ->
<id>md5</id> <repository>
<url>http://repo.md-5.net/content/groups/public/</url> <id>luricos.de-repo</id>
</repository> <url>http://repo.luricos.de/repository/bukkit-plugins/</url>
<!-- https://github.com/Hidendra/Plugin-Metrics/wiki/Usage --> </repository><!- - It points to dependencies that don't exist anymore -->
<repository> <!-- Official LogBlock repository -->
<id>Plugin Metrics</id> <repository>
<url>http://repo.mcstats.org/content/repositories/public</url> <id>md5</id>
</repository> <url>http://repo.md-5.net/content/groups/public/</url>
</repositories> </repository>
<!-- Official AuthMe Reloaded repository -->
<dependencies> <repository>
<dependency> <id>codemc-repo</id>
<groupId>de.jaschastarke</groupId> <url>https://repo.codemc.org/repository/maven-public/</url>
<artifactId>plib</artifactId> </repository>
<version>${plib.version}</version> <!-- Official CoreProtect repository -->
</dependency> <repository>
<dependency> <id>coreprotect-repo</id>
<!-- http://dl.bukkit.org/ --> <url>http://maven.playpro.com/</url>
<groupId>org.bukkit</groupId> </repository>
<artifactId>bukkit</artifactId> <!-- Official PermissionsEx repository -->
<version>${bukkit.version}</version> <repository>
</dependency> <id>pex-repo</id>
<dependency> <url>https://repo.glaremasters.me/repository/permissionsex/</url>
<!-- http://dev.bukkit.org/server-mods/worldguard/ --> </repository>
<groupId>com.sk89q</groupId> </repositories>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version> <pluginRepositories>
</dependency> <pluginRepository>
<dependency> <id>de-jas-rep</id>
<!-- http://dev.bukkit.org/server-mods/worldedit/ --> <url>http://repo.ja-s.de/mvn</url>
<groupId>com.sk89q</groupId> </pluginRepository>
<artifactId>worldedit</artifactId> </pluginRepositories>
<version>6.0.0-SNAPSHOT</version>
</dependency> <dependencies>
<dependency> <dependency>
<!-- http://dev.bukkit.org/server-mods/authme-reloaded/ --> <groupId>de.jaschastarke</groupId>
<groupId>uk.org.whoami</groupId> <artifactId>plib</artifactId>
<artifactId>authme</artifactId> <version>${plib.version}</version>
<version>2.9.5</version> </dependency>
</dependency> <dependency>
<dependency> <!-- http://dl.bukkit.org/ -->
<!-- http://dev.bukkit.org/server-mods/authme-reloaded/ --> <groupId>org.bukkit</groupId>
<groupId>fr.xephi</groupId> <artifactId>bukkit</artifactId>
<artifactId>authme</artifactId> <version>${bukkit.version}</version>
<version>3.0</version> </dependency>
</dependency> <dependency>
<dependency> <!-- http://dl.bukkit.org/ -->
<!-- http://dev.bukkit.org/server-mods/multiverse-core/ --> <groupId>org.bukkit.</groupId> <!-- Needed for WE integration -->
<groupId>com.onarandombox.multiversecore</groupId> <artifactId>bukkit</artifactId>
<artifactId>Multiverse-Core</artifactId> <version>1.14.4-R0.1-SNAPSHOT</version>
<version>2.4</version> </dependency>
</dependency> <dependency>
<dependency> <!-- http://dev.bukkit.org/server-mods/worldguard/ -->
<!-- http://dev.bukkit.org/bukkit-plugins/multiworld-v-2-0/ --> <groupId>com.sk89q.worldguard</groupId>
<groupId>multiworld</groupId> <artifactId>worldguard-bukkit</artifactId>
<artifactId>multiworld</artifactId> <version>7.0.0</version>
<version>4.7.2</version> </dependency>
</dependency> <dependency>
<dependency> <!-- http://dev.bukkit.org/server-mods/worldguard/ -->
<!-- http://dev.bukkit.org/server-mods/xauth/ --> <groupId>com.sk89q.worldedit</groupId>
<groupId>com.cypherx</groupId> <artifactId>worldedit-bukkit</artifactId>
<artifactId>xauth</artifactId> <version>7.0.0</version>
<version>2.0.26</version> </dependency>
</dependency> <dependency>
<dependency> <!-- http://dev.bukkit.org/server-mods/authme-reloaded/ -->
<!-- https://github.com/Hidendra/Plugin-Metrics/wiki/Usage --> <groupId>fr.xephi</groupId>
<groupId>org.mcstats.bukkit</groupId> <artifactId>authme</artifactId>
<artifactId>metrics</artifactId> <version>5.6.0-SNAPSHOT</version>
<version>R7</version> <scope>provided</scope>
<scope>compile</scope> </dependency>
</dependency> <dependency>
</dependencies> <!-- http://dev.bukkit.org/server-mods/multiverse-core/ -->
<groupId>com.onarandombox.multiversecore</groupId>
<build> <artifactId>Multiverse-Core</artifactId>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory> <version>2.4</version>
<finalName>${project.artifactId}</finalName> </dependency>
<dependency>
<plugins> <!-- http://dev.bukkit.org/bukkit-plugins/multiworld-v-2-0/ -->
<plugin> <groupId>multiworld</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>multiworld</artifactId>
<artifactId>maven-compiler-plugin</artifactId> <version>5.2.8</version>
<version>2.3.2</version> </dependency>
<configuration> <dependency>
<source>1.6</source> <!-- http://dev.bukkit.org/server-mods/xauth/ -->
<target>1.6</target> <groupId>de.luricos.bukkit</groupId>
<annotationProcessors> <artifactId>xAuth</artifactId>
<!-- Needed to fetch DocComments from Source --> <version>2.0.26</version>
<annotationProcessor>de.jaschastarke.maven.AnnotationProcessor</annotationProcessor> </dependency>
</annotationProcessors> <dependency>
</configuration> <!-- http://dev.bukkit.org/bukkit-plugins/coreprotect/ -->
</plugin> <groupId>net.coreprotect</groupId>
<plugin> <artifactId>coreprotect</artifactId>
<groupId>de.jaschastarke</groupId> <version>19.1</version>
<artifactId>plib</artifactId> </dependency>
<version>${plib.version}</version> <!-- https://mvnrepository.com/artifact/org.avaje/ebean -->
<executions> <dependency>
<execution> <groupId>org.avaje</groupId>
<phase>compile</phase> <artifactId>ebean</artifactId>
<goals> <version>2.7.3</version>
<goal>pluginyaml</goal> </dependency>
</goals> <dependency>
<configuration> <groupId>org.bstats</groupId>
<!-- plugin.yml --> <artifactId>bstats-bukkit</artifactId>
<mainClass>de.jaschastarke.minecraft.limitedcreative.LimitedCreative</mainClass> <version>2.2.1</version>
<softdepend> <scope>compile</scope>
<param>WorldGuard</param> </dependency>
<param>WorldEdit</param> </dependencies>
<param>Multiverse-Core</param>
<param>Multiworld</param> <build>
<param>xAuth</param> <sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<param>AuthMe</param> <finalName>${project.artifactId}</finalName>
<param>MultiInv</param>
<param>Multiverse-Inventories</param> <plugins>
<param>Vault</param> <plugin>
</softdepend> <groupId>org.apache.maven.plugins</groupId>
<custom> <artifactId>maven-compiler-plugin</artifactId>
<dev-url>http://dev.bukkit.org/server-mods/limited-creative/</dev-url> <version>3.8.1</version>
</custom> <configuration>
</configuration> <source>1.8</source>
</execution> <target>1.8</target>
</executions> <annotationProcessors>
</plugin> <!-- Needed to fetch DocComments from Source -->
<plugin> <annotationProcessor>de.jaschastarke.maven.AnnotationProcessor</annotationProcessor>
<groupId>org.apache.maven.plugins</groupId> </annotationProcessors>
<artifactId>maven-shade-plugin</artifactId> </configuration>
<version>2.0</version> </plugin>
<executions> <plugin>
<execution> <groupId>de.jaschastarke</groupId>
<phase>package</phase> <artifactId>plib</artifactId>
<goals> <version>${plib.version}</version>
<goal>shade</goal> <executions>
</goals> <execution>
<configuration> <phase>compile</phase>
<createDependencyReducedPom>false</createDependencyReducedPom> <goals>
<artifactSet> <goal>pluginyaml</goal>
<includes> </goals>
<include>de.jaschastarke:plib</include> <configuration>
<include>org.mcstats.*:*</include> <!-- plugin.yml -->
</includes> <mainClass>de.jaschastarke.minecraft.limitedcreative.LimitedCreative</mainClass>
</artifactSet> <softdepend>
<filters> <param>WorldGuard</param>
<filter> <param>WorldEdit</param>
<artifact>de.jaschastarke:plib</artifact> <param>Multiverse-Core</param>
<excludes> <param>Multiworld</param>
<exclude>de/jaschastarke/maven/**</exclude> <param>xAuth</param>
<exclude>de/jaschastarke/bukkit/maven/**</exclude> <param>AuthMe</param>
</excludes> <param>MultiInv</param>
</filter> <param>Multiverse-Inventories</param>
</filters> <param>Vault</param>
<relocations> <param>CoreProtect</param>
<relocation> </softdepend>
<pattern>org.mcstats</pattern> <custom>
<shadedPattern>de.jaschastarke.minecraft.limitedcreative.metrics</shadedPattern> <dev-url>http://dev.bukkit.org/server-mods/limited-creative/</dev-url>
</relocation> </custom>
</relocations> </configuration>
</configuration> </execution>
</execution> </executions>
</executions> </plugin>
</plugin> <plugin>
</plugins> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<pluginManagement> <version>3.2.4</version>
<plugins> <executions>
<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> <execution>
<plugin> <phase>package</phase>
<groupId>org.eclipse.m2e</groupId> <goals>
<artifactId>lifecycle-mapping</artifactId> <goal>shade</goal>
<version>1.0.0</version> </goals>
<configuration> <configuration>
<lifecycleMappingMetadata> <createDependencyReducedPom>false</createDependencyReducedPom>
<pluginExecutions> <artifactSet>
<pluginExecution> <includes>
<pluginExecutionFilter> <include>de.jaschastarke:plib</include>
<groupId>de.jaschastarke</groupId> <include>org.bstats</include>
<artifactId>plib</artifactId> </includes>
<versionRange> </artifactSet>
[0.1-SNAPSHOT,) <filters>
</versionRange> <filter>
<goals> <artifact>de.jaschastarke:plib</artifact>
<goal>pluginyaml</goal> <excludes>
</goals> <exclude>de/jaschastarke/maven/**</exclude>
</pluginExecutionFilter> <exclude>de/jaschastarke/bukkit/maven/**</exclude>
<action> </excludes>
<ignore></ignore> </filter>
</action> </filters>
</pluginExecution> <relocations>
</pluginExecutions> <relocation>
</lifecycleMappingMetadata> <pattern>org.bstats</pattern>
</configuration> <shadedPattern>de.jaschastarke.minecraft.limitedcreative.bstats</shadedPattern>
</plugin> </relocation>
</plugins> </relocations>
</pluginManagement> </configuration>
<extensions> </execution>
<!-- Enabling the use of SCP --> </executions>
<extension> </plugin>
<groupId>org.apache.maven.wagon</groupId> </plugins>
<artifactId>wagon-ssh</artifactId>
<version>1.0</version> <pluginManagement>
</extension> <plugins>
</extensions> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
</build> <plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>de.jaschastarke</groupId>
<artifactId>plib</artifactId>
<versionRange>
[0.1-SNAPSHOT,)
</versionRange>
<goals>
<goal>pluginyaml</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<extensions>
<!-- Enabling the use of SCP -->
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>2.1</version>
</extension>
</extensions>
</build>
</project> </project>

View file

@ -74,11 +74,11 @@ public class FeatureBlockItemSpawn extends CoreModule<LimitedCreative> implement
} }
public void block(Block block, Player player) { public void block(Block block, Player player) {
if (player.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH)) { if (player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH)) {
block(block.getLocation(), block.getType()); block(block.getLocation(), block.getType());
} else { } else {
// doesn't include silktouch // doesn't include silktouch
for (ItemStack i : block.getDrops(player.getItemInHand())) { for (ItemStack i : block.getDrops(player.getInventory().getItemInMainHand())) {
block(block.getLocation(), i.getType()); block(block.getLocation(), i.getType());
} }
} }

View file

@ -1,70 +1,46 @@
package de.jaschastarke.minecraft.limitedcreative; package de.jaschastarke.minecraft.limitedcreative;
import java.io.IOException;
import org.bukkit.event.Listener;
import org.mcstats.Metrics;
import de.jaschastarke.bukkit.lib.CoreModule; import de.jaschastarke.bukkit.lib.CoreModule;
import de.jaschastarke.bukkit.tools.stats.IStatistics;
import de.jaschastarke.bukkit.tools.stats.PiwikStatistics;
import de.jaschastarke.modularize.IModule; import de.jaschastarke.modularize.IModule;
import de.jaschastarke.modularize.ModuleEntry; import de.jaschastarke.modularize.ModuleEntry;
import de.jaschastarke.modularize.ModuleEntry.ModuleState; import de.jaschastarke.modularize.ModuleEntry.ModuleState;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.AdvancedPie;
import org.bukkit.event.Listener;
import java.util.HashMap;
public class FeatureMetrics extends CoreModule<LimitedCreative> implements Listener { public class FeatureMetrics extends CoreModule<LimitedCreative> implements Listener {
public FeatureMetrics(LimitedCreative plugin) { public FeatureMetrics(LimitedCreative plugin) {
super(plugin); super(plugin);
} }
private IStatistics metric;
private Metrics mcstats = null; private Metrics bstats = null;
@Override @Override
public void onEnable() { public void onEnable() {
super.onEnable(); super.onEnable();
metric = new PiwikStatistics(plugin); if (bstats == null) {
if (mcstats == null) { bstats = new Metrics(plugin, 10413);
try {
mcstats = new Metrics(plugin); bstats.addCustomChart(new AdvancedPie("module_usage", () -> {
HashMap<String, Integer> ret = new HashMap<>();
Metrics.Graph moduleGraph = mcstats.createGraph("Module Usage"); for (final ModuleEntry<IModule> mod : plugin.getModules())
for (final ModuleEntry<IModule> mod : plugin.getModules()) { if (mod.getModule() instanceof CoreModule<?>)
if (mod.getModule() instanceof CoreModule<?>) { ret.put(((CoreModule<?>) mod.getModule()).getName(), mod.getState() == ModuleState.ENABLED ? 1 : 0);
moduleGraph.addPlotter(new Metrics.Plotter(((CoreModule<?>) mod.getModule()).getName()) { return ret;
@Override }));
public int getValue() { bstats.addCustomChart(new AdvancedPie("dependencies", () -> {
return mod.getState() == ModuleState.ENABLED ? 1 : 0; HashMap<String, Integer> ret = new HashMap<>();
} for (final String dep : plugin.getDescription().getSoftDepend())
}); ret.put(dep, plugin.getServer().getPluginManager().isPluginEnabled(dep) ? 1 : 0);
} return ret;
} }));
Metrics.Graph depGraph = mcstats.createGraph("Dependencies");
for (final String dep : plugin.getDescription().getSoftDepend()) {
depGraph.addPlotter(new Metrics.Plotter(dep) {
@Override
public int getValue() {
return plugin.getServer().getPluginManager().isPluginEnabled(dep) ? 1 : 0;
}
});
}
mcstats.start();
} catch (IOException e) {
// Failed to submit the stats :-(
getLog().warn("MCStats-Error: " + e.getMessage());
}
} }
} }
@Override @Override
public void onDisable() { public void onDisable() {
super.onDisable(); super.onDisable();
metric.unregister();
}
public void track(String event) throws IOException {
if (metric == null)
throw new IllegalAccessError("The feature hasn't been enabled");
metric.trackEvent(event);
} }
} }

View file

@ -1,13 +1,12 @@
package de.jaschastarke.minecraft.limitedcreative; package de.jaschastarke.minecraft.limitedcreative;
import org.bukkit.Bukkit;
import de.jaschastarke.hooking.BooleanHooker; import de.jaschastarke.hooking.BooleanHooker;
import de.jaschastarke.hooking.GetHooker; import de.jaschastarke.hooking.GetHooker;
import de.jaschastarke.minecraft.limitedcreative.hooks.MultiVerseHooks; import de.jaschastarke.minecraft.limitedcreative.hooks.MultiVerseHooks;
import de.jaschastarke.minecraft.limitedcreative.hooks.PlayerCheckHooker; import de.jaschastarke.minecraft.limitedcreative.hooks.PlayerCheckHooker;
import de.jaschastarke.minecraft.limitedcreative.hooks.WorldTypeHooker; import de.jaschastarke.minecraft.limitedcreative.hooks.WorldTypeHooker;
import de.jaschastarke.minecraft.limitedcreative.hooks.xAuthHooks; import de.jaschastarke.minecraft.limitedcreative.hooks.xAuthHooks;
import org.bukkit.Bukkit;
public final class Hooks { public final class Hooks {
public static PlayerCheckHooker IsLoggedIn = new PlayerCheckHooker(true); public static PlayerCheckHooker IsLoggedIn = new PlayerCheckHooker(true);
@ -53,7 +52,8 @@ public final class Hooks {
public static boolean isAuthMePresent() { public static boolean isAuthMePresent() {
if (isPluginEnabled("AuthMe")) { if (isPluginEnabled("AuthMe")) {
try { try {
return Class.forName("uk.org.whoami.authme.api.API") != null; Class.forName("uk.org.whoami.authme.api.API");
return true;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return false; return false;
} }
@ -64,7 +64,8 @@ public final class Hooks {
public static boolean isXAuth20Present() { public static boolean isXAuth20Present() {
if (isPluginEnabled("xAuth")) { if (isPluginEnabled("xAuth")) {
try { try {
return Class.forName("com.cypherx.xauth.xAuth") != null; Class.forName("com.cypherx.xauth.xAuth");
return true;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return false; return false;
} }

View file

@ -1,140 +1,135 @@
package de.jaschastarke.minecraft.limitedcreative; package de.jaschastarke.minecraft.limitedcreative;
import java.io.File; import de.jaschastarke.bukkit.lib.CoreModule;
import java.util.Map; import de.jaschastarke.minecraft.limitedcreative.inventories.*;
import java.util.WeakHashMap; import de.jaschastarke.minecraft.limitedcreative.inventories.store.PlayerInventoryStorage;
import de.jaschastarke.minecraft.limitedcreative.inventories.store.ReflectionStorage;
import org.bukkit.GameMode; import de.jaschastarke.modularize.IModule;
import org.bukkit.entity.Player; import de.jaschastarke.modularize.ModuleEntry;
import org.bukkit.inventory.ItemStack; import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import de.jaschastarke.bukkit.lib.CoreModule; import org.bukkit.inventory.ItemStack;
import de.jaschastarke.minecraft.limitedcreative.inventories.ArmoryConfig;
import de.jaschastarke.minecraft.limitedcreative.inventories.Inventory; import java.io.File;
import de.jaschastarke.minecraft.limitedcreative.inventories.InventoryConfig; import java.util.Map;
import de.jaschastarke.minecraft.limitedcreative.inventories.InventoryPermissions; import java.util.WeakHashMap;
import de.jaschastarke.minecraft.limitedcreative.inventories.PlayerListener;
import de.jaschastarke.minecraft.limitedcreative.inventories.store.InvYamlStorage; public class ModInventories extends CoreModule<LimitedCreative> {
import de.jaschastarke.minecraft.limitedcreative.inventories.store.PlayerInventoryStorage; protected PlayerInventoryStorage storage;
import de.jaschastarke.modularize.IModule; protected Map<Player, Inventory> inventories;
import de.jaschastarke.modularize.ModuleEntry; protected InventoryConfig config;
protected ArmoryConfig armor_config;
public class ModInventories extends CoreModule<LimitedCreative> {
protected PlayerInventoryStorage storage; public ModInventories(LimitedCreative plugin) {
protected Map<Player, Inventory> inventories; super(plugin);
protected InventoryConfig config; }
protected ArmoryConfig armor_config; @Override
public String getName() {
public ModInventories(LimitedCreative plugin) { return "Inventory";
super(plugin); }
}
@Override @Override
public String getName() { public void initialize(ModuleEntry<IModule> entry) {
return "Inventory"; super.initialize(entry);
} listeners.addListener(new PlayerListener(this));
config = plugin.getPluginConfig().registerSection(new InventoryConfig(this, entry));
@SuppressWarnings("deprecation") armor_config = config.registerSection(new ArmoryConfig(this));
@Override
public void initialize(ModuleEntry<IModule> entry) { if (Hooks.isAuthMePresent()) {
super.initialize(entry); addModule(new de.jaschastarke.minecraft.limitedcreative.inventories.AuthMeInventories(plugin, this));
listeners.addListener(new PlayerListener(this)); }
config = plugin.getPluginConfig().registerSection(new InventoryConfig(this, entry)); String incomp = Hooks.InventoryIncompatible.test();
armor_config = config.registerSection(new ArmoryConfig(this)); if (config.getEnabled() && incomp != null) {
getLog().warn(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName()));
if (Hooks.isAuthMePresent()) { entry.deactivateUsage();
addModule(new de.jaschastarke.minecraft.limitedcreative.inventories.AuthMeInventories(plugin, this)); }
} }
String incomp = Hooks.InventoryIncompatible.test(); @Override
if (config.getEnabled() && incomp != null) { public void onEnable() {
getLog().warn(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName())); String incomp = Hooks.InventoryIncompatible.test();
entry.deactivateUsage(); if (incomp != null) {
} throw new IllegalAccessError(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName()));
} }
@Override super.onEnable();
public void onEnable() { //storage = new InvYamlStorage(this, new File(plugin.getDataFolder(), config.getFolder()));
String incomp = Hooks.InventoryIncompatible.test(); storage = new ReflectionStorage(this, new File(plugin.getDataFolder(), config.getFolder()));
if (incomp != null) { inventories = new WeakHashMap<Player, Inventory>();
throw new IllegalAccessError(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName())); getLog().info(plugin.getLocale().trans("basic.loaded.module"));
} }
super.onEnable(); public InventoryConfig getConfig() {
storage = new InvYamlStorage(this, new File(plugin.getDataFolder(), config.getFolder())); return config;
inventories = new WeakHashMap<Player, Inventory>(); }
getLog().info(plugin.getLocale().trans("basic.loaded.module")); public ArmoryConfig getArmorConfig() {
} return armor_config;
public InventoryConfig getConfig() { }
return config;
} public PlayerInventoryStorage getStorage() {
public ArmoryConfig getArmorConfig() { return storage;
return armor_config; }
}
public Inventory getInventory(Player player) {
public PlayerInventoryStorage getStorage() { if (inventories.containsKey(player)) {
return storage; return inventories.get(player);
} } else {
Inventory inv = new Inventory(storage, player);
public Inventory getInventory(Player player) { inventories.put(player, inv);
if (inventories.containsKey(player)) { return inv;
return inventories.get(player); }
} else { }
Inventory inv = new Inventory(storage, player);
inventories.put(player, inv); public void onSetGameMode(Player player, GameMode gm) {
return inv; if (plugin.getPermManager().hasPermission(player, InventoryPermissions.KEEP_INVENTORY))
} return;
} player.closeInventory();
public void onSetGameMode(Player player, GameMode gm) { GameMode cgm = player.getGameMode();
if (plugin.getPermManager().hasPermission(player, InventoryPermissions.KEEP_INVENTORY)) if (gm == GameMode.ADVENTURE && !config.getSeparateAdventure())
return; gm = GameMode.SURVIVAL;
player.closeInventory(); else if (gm == GameMode.SPECTATOR)
gm = GameMode.CREATIVE;
GameMode cgm = player.getGameMode(); if (cgm == GameMode.ADVENTURE && !config.getSeparateAdventure())
if (gm == GameMode.ADVENTURE && !config.getSeparateAdventure()) cgm = GameMode.SURVIVAL;
gm = GameMode.SURVIVAL; else if (cgm == GameMode.SPECTATOR)
else if (gm == GameMode.SPECTATOR) cgm = GameMode.CREATIVE;
gm = GameMode.CREATIVE;
if (cgm == GameMode.ADVENTURE && !config.getSeparateAdventure()) if (gm != cgm) {
cgm = GameMode.SURVIVAL; if (gm != GameMode.CREATIVE || config.getStoreCreative()) {
else if (cgm == GameMode.SPECTATOR) getInventory(player).save(cgm);
cgm = GameMode.CREATIVE; }
if (gm == GameMode.CREATIVE) {
if (gm != cgm) { if (config.getStoreCreative() && getInventory(player).isStored(GameMode.CREATIVE)) {
if (gm != GameMode.CREATIVE || config.getStoreCreative()) { getInventory(player).load(GameMode.CREATIVE);
getInventory(player).save(cgm); } else {
} getInventory(player).clear();
if (gm == GameMode.CREATIVE) { }
if (config.getStoreCreative() && getInventory(player).isStored(GameMode.CREATIVE)) { setCreativeArmor(player);
getInventory(player).load(GameMode.CREATIVE); } else if (gm == GameMode.SURVIVAL) {
} else { if (getInventory(player).isStored(GameMode.SURVIVAL))
getInventory(player).clear(); getInventory(player).load(GameMode.SURVIVAL);
} } else if (gm == GameMode.ADVENTURE) {
setCreativeArmor(player); if (getInventory(player).isStored(GameMode.ADVENTURE))
} else if (gm == GameMode.SURVIVAL) { getInventory(player).load(GameMode.ADVENTURE);
if (getInventory(player).isStored(GameMode.SURVIVAL)) else
getInventory(player).load(GameMode.SURVIVAL); getInventory(player).clear();
} else if (gm == GameMode.ADVENTURE) { }
if (getInventory(player).isStored(GameMode.ADVENTURE)) }
getInventory(player).load(GameMode.ADVENTURE); }
else
getInventory(player).clear(); public void setCreativeArmor(Player player) {
} if (!getPlugin().getPermManager().hasPermission(player, InventoryPermissions.BYPASS_CREATIVE_ARMOR)) {
} Map<String, ItemStack> armor = armor_config.getCreativeArmor();
} if (armor != null) {
ItemStack[] is = new ItemStack[4];
public void setCreativeArmor(Player player) { if (armor.containsKey("feet"))
if (!getPlugin().getPermManager().hasPermission(player, InventoryPermissions.BYPASS_CREATIVE_ARMOR)) { is[0] = armor.get("feet");
Map<String, ItemStack> armor = armor_config.getCreativeArmor(); if (armor.containsKey("legs"))
if (armor != null) { is[1] = armor.get("legs");
ItemStack[] is = new ItemStack[4]; if (armor.containsKey("chest"))
if (armor.containsKey("feet")) is[2] = armor.get("chest");
is[0] = armor.get("feet"); if (armor.containsKey("head"))
if (armor.containsKey("legs")) is[3] = armor.get("head");
is[1] = armor.get("legs"); player.getInventory().setArmorContents(is);
if (armor.containsKey("chest")) }
is[2] = armor.get("chest"); }
if (armor.containsKey("head")) }
is[3] = armor.get("head"); }
player.getInventory().setArmorContents(is);
}
}
}
}

View file

@ -1,6 +1,5 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate; package de.jaschastarke.minecraft.limitedcreative.blockstate;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -144,19 +143,15 @@ public class BlockListener implements Listener {
return; return;
event.getBlock().setMetadata("LCBS_pistonIsAlreadyExtended", blockAlreadExtended); event.getBlock().setMetadata("LCBS_pistonIsAlreadyExtended", blockAlreadExtended);
Block source = event.getBlock().getRelative(event.getDirection());
/*if (mod.isDebug()) /*if (mod.isDebug())
mod.getLog().debug("PistonExtend "+source.getType()+" "+source.getLocation()+" "+event.getDirection());*/ mod.getLog().debug("PistonExtend "+source.getType()+" "+source.getLocation()+" "+event.getDirection());*/
List<Block> movedBlocks = new ArrayList<Block>(); List<Block> movedBlocks = event.getBlocks();
while (source != null && source.getType() != Material.AIR) {
movedBlocks.add(0, source); // put on top, so iterating the
source = source.getRelative(event.getDirection());
}
if (movedBlocks.size() > 0) { if (movedBlocks.size() > 0) {
DBTransaction update = mod.getModel().groupUpdate(); DBTransaction update = mod.getModel().groupUpdate();
for (Block sblock : movedBlocks) { for(int count = movedBlocks.size()-1; count >= 0; count--){
Block sblock = movedBlocks.get(count);
Block dest = sblock.getRelative(event.getDirection()); Block dest = sblock.getRelative(event.getDirection());
if (mod.isDebug()) if (mod.isDebug())
mod.getLog().debug("PistionExtend moves "+sblock.getType()+"-Block from "+sblock.getLocation()+" to "+dest.getLocation()); mod.getLog().debug("PistionExtend moves "+sblock.getType()+"-Block from "+sblock.getLocation()+" to "+dest.getLocation());
@ -173,12 +168,19 @@ public class BlockListener implements Listener {
return; return;
event.getBlock().removeMetadata("LCBS_pistonIsAlreadyExtended", mod.getPlugin()); event.getBlock().removeMetadata("LCBS_pistonIsAlreadyExtended", mod.getPlugin());
Block dest = event.getBlock().getRelative(event.getDirection()); List<Block> movedBlocks = event.getBlocks();
Block source = dest.getRelative(event.getDirection()); if(movedBlocks.size() > 0)
if (event.isSticky() && source.getType() != Material.AIR) { {
if (mod.isDebug()) DBTransaction update = mod.getModel().groupUpdate();
mod.getLog().debug("PistionRetract moves "+source.getType()+"-Block from "+source.getLocation()+" to "+dest.getLocation()); for(int count = movedBlocks.size()-1; count >= 0; count--){
mod.getModel().moveState(source, source.getRelative(event.getDirection().getOppositeFace())); Block sblock = movedBlocks.get(count);
Block dest = sblock.getRelative(event.getDirection());
if (mod.isDebug())
mod.getLog().debug("PistionRetract moves "+sblock.getType()+"-Block from "+sblock.getLocation()+" to "+dest.getLocation());
update.moveState(sblock, dest);
}
update.finish();
} }
} }
} }

View file

@ -1,6 +1,7 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate; package de.jaschastarke.minecraft.limitedcreative.blockstate;
import java.util.Date; import java.util.Date;
import java.util.UUID;
import javax.persistence.Column; import javax.persistence.Column;
//import javax.persistence.EmbeddedId; //import javax.persistence.EmbeddedId;
@ -37,7 +38,7 @@ public class BlockState {
private GameMode gameMode; private GameMode gameMode;
@Column(name = "player") @Column(name = "player")
private String playerName; private UUID uuid;
@NotNull @NotNull
@Column(name = "cdate") @Column(name = "cdate")
@ -51,7 +52,7 @@ public class BlockState {
public BlockState(BlockState copy) { public BlockState(BlockState copy) {
this.location = copy.location; this.location = copy.location;
this.gameMode = copy.gameMode; this.gameMode = copy.gameMode;
this.playerName = copy.playerName; this.uuid = copy.uuid;
this.date = copy.date; this.date = copy.date;
this.source = copy.source; this.source = copy.source;
} }
@ -72,24 +73,35 @@ public class BlockState {
this.gameMode = gm; this.gameMode = gm;
} }
public String getPlayerName() { public UUID getPlayerUUID() {
return playerName; return uuid;
} }
public void setPlayerName(String s) { public String getPlayerName() {
playerName = s; return Bukkit.getOfflinePlayer(uuid).getName();
}
//TODO Rename
@SuppressWarnings("deprecation")
public void setPlayerNameOrUUID(String s) {
if(s==null)
uuid=null;
else if(!s.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"))
uuid = Bukkit.getOfflinePlayer(s).getUniqueId(); //If it's a name, get UUID
else
uuid = UUID.fromString(s);
} }
public OfflinePlayer getPlayer() { public OfflinePlayer getPlayer() {
OfflinePlayer p = Bukkit.getPlayerExact(playerName); OfflinePlayer p = Bukkit.getPlayer(uuid);
if (p == null) if (p == null)
p = Bukkit.getOfflinePlayer(playerName); p = Bukkit.getOfflinePlayer(uuid);
return p; return p;
} }
public void setPlayer(OfflinePlayer player) { public void setPlayer(OfflinePlayer player) {
setSource(Source.PLAYER); setSource(Source.PLAYER);
this.playerName = player.getName(); this.uuid = player.getUniqueId();
if (player instanceof Player) { if (player instanceof Player) {
setGameMode(((Player) player).getGameMode()); setGameMode(((Player) player).getGameMode());
} }
@ -109,7 +121,7 @@ public class BlockState {
public void setSource(Source source) { public void setSource(Source source) {
if (source != Source.PLAYER && source != Source.EDIT && source != Source.COMMAND) if (source != Source.PLAYER && source != Source.EDIT && source != Source.COMMAND)
setPlayerName(null); setPlayerNameOrUUID(null);
this.source = source; this.source = source;
} }
@ -119,6 +131,7 @@ public class BlockState {
@Override @Override
public String toString() { public String toString() {
String playerName = Bukkit.getOfflinePlayer(uuid).getName();
//return blockLocation.toString() + " by " + //return blockLocation.toString() + " by " +
return location.toString() + " by " + return location.toString() + " by " +
(source == Source.PLAYER ? playerName : (source.toString() + (playerName != null ? "(" + playerName + ")" : ""))) + (source == Source.PLAYER ? playerName : (source.toString() + (playerName != null ? "(" + playerName + ")" : ""))) +

View file

@ -1,287 +1,285 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate; package de.jaschastarke.minecraft.limitedcreative.blockstate;
import java.util.Date; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import org.bukkit.Bukkit; import com.sk89q.worldedit.bukkit.BukkitPlayer;
import org.bukkit.GameMode; import com.sk89q.worldedit.math.BlockVector3;
import org.bukkit.Location; import com.sk89q.worldedit.regions.Region;
import org.bukkit.Material; import com.sk89q.worldedit.world.World;
import org.bukkit.World; import de.jaschastarke.LocaleString;
import org.bukkit.scheduler.BukkitRunnable; import de.jaschastarke.bukkit.lib.chat.ChatFormattings;
import de.jaschastarke.bukkit.lib.commands.*;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand;
import com.sk89q.worldedit.bukkit.selections.Selection; import de.jaschastarke.bukkit.lib.commands.annotations.Usages;
import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser;
import de.jaschastarke.LocaleString; import de.jaschastarke.bukkit.lib.database.DBHelper;
import de.jaschastarke.bukkit.lib.chat.ChatFormattings; import de.jaschastarke.database.DatabaseConfigurationException;
import de.jaschastarke.bukkit.lib.commands.BukkitCommand; import de.jaschastarke.database.db.Database;
import de.jaschastarke.bukkit.lib.commands.CommandContext; import de.jaschastarke.maven.ArchiveDocComments;
import de.jaschastarke.bukkit.lib.commands.CommandException; import de.jaschastarke.maven.PluginCommand;
import de.jaschastarke.bukkit.lib.commands.HelpCommand; import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import de.jaschastarke.bukkit.lib.commands.IHelpDescribed; import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
import de.jaschastarke.bukkit.lib.commands.MissingPermissionCommandException; import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source;
import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand; import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid;
import de.jaschastarke.bukkit.lib.commands.annotations.Usages; import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.DBTransaction;
import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser; import de.jaschastarke.modularize.ModuleEntry.ModuleState;
import de.jaschastarke.bukkit.lib.database.DBHelper; import org.bukkit.Bukkit;
import de.jaschastarke.database.DatabaseConfigurationException; import org.bukkit.GameMode;
import de.jaschastarke.database.db.Database; import org.bukkit.Location;
import de.jaschastarke.maven.ArchiveDocComments;
import de.jaschastarke.maven.PluginCommand; import java.util.Date;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates; /**
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source; * LimitedCreative-BlockState-Command: modify blockstate database to prevent drops of selected blocks (requires WorldEdit)
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid; * @usage /<command> - displays Regions-Command-Help
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.DBTransaction; * @permission limitedcreative.blockstate.command
import de.jaschastarke.modularize.ModuleEntry.ModuleState; */
@ArchiveDocComments
/** @PluginCommand
* LimitedCreative-BlockState-Command: modify blockstate database to prevent drops of selected blocks (requires WorldEdit) public class BlockStateCommand extends BukkitCommand implements IHelpDescribed {
* @usage /<command> - displays Regions-Command-Help private ModBlockStates mod;
* @permission limitedcreative.blockstate.command private HelpCommand help;
*/
@ArchiveDocComments public BlockStateCommand() {
@PluginCommand this.help = this.getDefaultHelpCommand();
public class BlockStateCommand extends BukkitCommand implements IHelpDescribed { }
private ModBlockStates mod; public BlockStateCommand(ModBlockStates mod) {
private HelpCommand help; super(mod.getPlugin());
this.help = this.getDefaultHelpCommand();
public BlockStateCommand() { this.mod = mod;
this.help = this.getDefaultHelpCommand(); }
}
public BlockStateCommand(ModBlockStates mod) { @Override
super(mod.getPlugin()); public String getName() {
this.help = this.getDefaultHelpCommand(); return "lcbs";
this.mod = mod; }
}
@Override
@Override public String[] getAliases() {
public String getName() { return new String[]{};
return "lcbs"; }
}
/**
@Override * @internal has no effect, as not tested by any command handler
public String[] getAliases() { * @see IHelpDescribed
return new String[]{}; */
} @Override
public IAbstractPermission[] getRequiredPermissions() {
/** return new IAbstractPermission[]{BlockStatePermissions.COMMAND};
* @internal has no effect, as not tested by any command handler }
* @see IHelpDescribed
*/ @Override
@Override public CharSequence[] getUsages() {
public IAbstractPermission[] getRequiredPermissions() { return new String[]{"..."};
return new IAbstractPermission[]{BlockStatePermissions.COMMAND}; }
}
@Override
@Override public CharSequence getDescription() {
public CharSequence[] getUsages() { return new LocaleString("command.blockstate");
return new String[]{"..."}; }
}
@Override
@Override public CharSequence getPackageName() {
public CharSequence getDescription() { return mod.getPlugin().getName() + " - " + mod.getName();
return new LocaleString("command.blockstate"); }
}
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException {
@Override if (mod.getModuleEntry().getState() != ModuleState.ENABLED)
public CharSequence getPackageName() { throw new CommandException("Module " + mod.getName() + " is disabled");
return mod.getPlugin().getName() + " - " + mod.getName(); return super.execute(context, args);
} }
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException { /**
if (mod.getModuleEntry().getState() != ModuleState.ENABLED) * Deletes no longer used data from the BlockState-Database. Currently it only removes non-creative entries
throw new CommandException("Module " + mod.getName() + " is disabled"); * from the database, if you changed to "logSurvival"-config from true to false.
return super.execute(context, args); */
} @IsCommand("cleanup")
@Usages("")
/** public boolean cleanupDatabase(final CommandContext context, String... args) throws CommandException {
* Deletes no longer used data from the BlockState-Database. Currently it only removes non-creative entries if (mod.getConfig().getLogSurvival()) {
* from the database, if you changed to "logSurvival"-config from true to false. context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.nothing_to_cleanup"));
*/ } else {
@IsCommand("cleanup") mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new Runnable() {
@Usages("") @Override
public boolean cleanupDatabase(final CommandContext context, String... args) throws CommandException { public void run() {
if (mod.getConfig().getLogSurvival()) { int countDeleted = mod.getModel().cleanUp(DBModel.Cleanup.SURVIVAL);
context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.nothing_to_cleanup")); if (countDeleted < 0)
} else { context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.cleanup_error"));
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new BukkitRunnable() { else
@Override context.responseFormatted(ChatFormattings.SUCCESS, L("command.blockstate.cleanup_success", countDeleted));
public void run() { }
int countDeleted = mod.getModel().cleanUp(DBModel.Cleanup.SURVIVAL); });
if (countDeleted < 0) }
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.cleanup_error")); return true;
else }
context.responseFormatted(ChatFormattings.SUCCESS, L("command.blockstate.cleanup_success", countDeleted));
} /**
}); * Modifies the BlockState-Database and sets all blocks in the selection to the provided gamemode. Set it
} * to "creative" to disable drop of this block on destroying. Set it to "survival" to allow it.
return true; * WorldEdit is required, because the selection Region is used.
} * gamemode can be: survival / creative / adventure / s / c / a / 0 / 1 / 2
* @throws MissingPermissionCommandException
/** */
* Modifies the BlockState-Database and sets all blocks in the selection to the provided gamemode. Set it @IsCommand("set")
* to "creative" to disable drop of this block on destroying. Set it to "survival" to allow it. @Usages("<gamemode>")
* WorldEdit is required, because the selection Region is used. public boolean setGameMode(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException {
* gamemode can be: survival / creative / adventure / s / c / a / 0 / 1 / 2 if (!mod.getPlugin().getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
* @throws MissingPermissionCommandException help.execute(context, new String[]{"set"});
*/ context.response(L("command.blockstate.requires_worldedit"));
@IsCommand("set") return true;
@Usages("<gamemode>") }
public boolean setGameMode(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException { if (!context.isPlayer()) {
if (!mod.getPlugin().getServer().getPluginManager().isPluginEnabled("WorldEdit")) { context.response(L("cmdblock.blocked.not_console"));
help.execute(context, new String[]{"set"}); return true;
context.response(L("command.blockstate.requires_worldedit")); }
return true; if (args.length < 1) {// doesn't count parameters
} return false;
if (!context.isPlayer()) { }
context.response(L("cmdblock.blocked.not_console")); if (mod.getConfig().getIgnoredWorlds().contains(context.getPlayer().getWorld().getName())) {
return true; context.response(L("command.blockstate.world_ignored", context.getPlayer().getWorld().getName()));
} return true;
if (args.length < 1) {// doesn't count parameters }
return false; String gm = args[0].toLowerCase();
} final GameMode tgm;
if (mod.getConfig().getIgnoredWorlds().contains(context.getPlayer().getWorld().getName())) { if (gm.equals("0") || gm.equals("s") || gm.equals("survival"))
context.response(L("command.blockstate.world_ignored", context.getPlayer().getWorld().getName())); tgm = GameMode.SURVIVAL;
return true; else if (gm.equals("1") || gm.equals("c") || gm.equals("creative"))
} tgm = GameMode.CREATIVE;
String gm = args[0].toLowerCase(); else if (gm.equals("2") || gm.equals("a") || gm.equals("adventure"))
final GameMode tgm; tgm = GameMode.ADVENTURE;
if (gm.equals("0") || gm.equals("s") || gm.equals("survival")) else {
tgm = GameMode.SURVIVAL; return false;
else if (gm.equals("1") || gm.equals("c") || gm.equals("creative")) }
tgm = GameMode.CREATIVE;
else if (gm.equals("2") || gm.equals("a") || gm.equals("adventure")) BukkitPlayer bp = BukkitAdapter.adapt(context.getPlayer());
tgm = GameMode.ADVENTURE; Region region = null;
else { try {
return false; region = WorldEdit.getInstance().getSessionManager().get(bp).getSelection(bp.getWorld());
} } catch (Exception ignored) { //IncompleteRegionException
}
WorldEditPlugin we = (WorldEditPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin("WorldEdit");
final Selection selection = we.getSelection(context.getPlayer()); final Region selection = region;
if (selection == null) {
if (selection == null) { context.response(L("command.blockstate.worledit_selection_empty"));
context.response(L("command.blockstate.worledit_selection_empty")); return true;
return true; }
}
final BlockVector3 min = selection.getMinimumPoint();
final Location min = selection.getMinimumPoint(); final BlockVector3 max = selection.getMaximumPoint();
final Location max = selection.getMaximumPoint();
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), () -> {
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new BukkitRunnable() { if (mod.isDebug())
@Override mod.getLog().debug("Scheduler: Asynchronous Task run");
public void run() { DBTransaction update = mod.getModel().groupUpdate();
if (mod.isDebug()) int count = 0;
mod.getLog().debug("Scheduler: Asynchronous Task run"); World w = selection.getWorld();
DBTransaction update = mod.getModel().groupUpdate(); assert w != null;
int count = 0; org.bukkit.World bw = BukkitAdapter.adapt(w);
World w = selection.getWorld();
Cuboid c = new Cuboid();
Cuboid c = new Cuboid(); c.add(new Location(bw, min.getBlockX(), min.getBlockY(), min.getBlockZ()));
c.add(min); c.add(new Location(bw, max.getBlockX(), max.getBlockY(), max.getBlockZ()));
c.add(max); mod.getModel().cacheStates(c);
mod.getModel().cacheStates(c);
BlockState seed = new BlockState();
BlockState seed = new BlockState(); seed.setPlayer(context.getPlayer());
seed.setPlayer(context.getPlayer()); seed.setGameMode(tgm);
seed.setGameMode(tgm); seed.setSource(Source.COMMAND);
seed.setSource(Source.COMMAND); seed.setDate(new Date());
seed.setDate(new Date()); for (int x = min.getBlockX(); x <= max.getBlockX(); x++) {
for (int x = min.getBlockX(); x <= max.getBlockX(); x++) { for (int y = min.getBlockY(); y <= max.getBlockY(); y++) {
for (int y = min.getBlockY(); y <= max.getBlockY(); y++) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) {
for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { BlockVector3 loc = BlockVector3.at(x, y, z);
Location loc = new Location(w, x, y, z); if (!w.getBlock(loc).getBlockType().getMaterial().isAir() && selection.contains(loc)) {
if (w.getBlockAt(loc).getType() != Material.AIR && selection.contains(loc)) { seed.setLocation(new Location(bw, x, y, z));
seed.setLocation(loc); update.setState(new BlockState(seed));
update.setState(new BlockState(seed)); count++;
count++; }
} }
} }
} }
} update.finish();
update.finish();
context.response(L("command.blockstate.command_updated", count));
context.response(L("command.blockstate.command_updated", count)); });
} return true;
}); }
return true;
} /**
* Imports BlockState Data from a given Database to the current active Database.
/** * A Server-Restart is needed after migration!
* Imports BlockState Data from a given Database to the current active Database. * Parameters:
* A Server-Restart is needed after migration! * -u --update Don't delete existing records / only overwrite if newer
* Parameters: * --import=<type> Import from other Plugins. Supported Types:
* -u --update Don't delete existing records / only overwrite if newer * cc CreativeControl
* --import=<type> Import from other Plugins. Supported Types: */
* cc CreativeControl @IsCommand("migrate")
*/ @Usages("-u --import=cc <dsn> [username] [password]")
@IsCommand("migrate") public boolean migrateDatabase(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException {
@Usages("-u --import=cc <dsn> [username] [password]") DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"debug", "d", "update", "u", "confirm"});
public boolean migrateDatabase(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException { if (params.getArgumentCount() < 1) {// doesn't count parameters
DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"debug", "d", "update", "u", "confirm"}); return false;
if (params.getArgumentCount() < 1) {// doesn't count parameters }
return false;
} if (Bukkit.getServer().getOnlinePlayers().size() > (context.isPlayer() ? 1 : 0)) {
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_useronline_error"));
if (Bukkit.getServer().getOnlinePlayers().size() > (context.isPlayer() ? 1 : 0)) { return true;
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_useronline_error")); }
return true;
} Database source;
Database target;
Database source; try {
Database target;
try { if (params.getArgumentCount() < 2)
source = DBHelper.createConnection(params.getArgument(0));
if (params.getArgumentCount() < 2) else if (params.getArgumentCount() < 3)
source = DBHelper.createConnection(params.getArgument(0)); source = DBHelper.createConnection(params.getArgument(0), params.getArgument(1), null);
else if (params.getArgumentCount() < 3) else
source = DBHelper.createConnection(params.getArgument(0), params.getArgument(1), null); source = DBHelper.createConnection(params.getArgument(0), params.getArgument(1), params.getArgument(2));
else
source = DBHelper.createConnection(params.getArgument(0), params.getArgument(1), params.getArgument(2)); target = mod.getPlugin().getDatabaseConnection();
} catch (DatabaseConfigurationException e) {
target = mod.getPlugin().getDatabaseConnection(); context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_connect_error", e.getMessage()));
} catch (DatabaseConfigurationException e) { return true;
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_connect_error", e.getMessage())); }
return true;
} DatabaseMigrationThread thread;
if (params.getParameter("import") != null) {
DatabaseMigrationThread thread; if (params.getParameter("import").equals("cc")) {
if (params.getParameter("import") != null) { thread = new CreativeControlImportThread(mod, context, source, target);
if (params.getParameter("import").equals("cc")) { } else {
thread = new CreativeControlImportThread(mod, context, source, target); context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_importtype_error", params.getParameter("import")));
} else { return false;
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.migrate_importtype_error", params.getParameter("import"))); }
return false; } else {
} thread = new DatabaseMigrationThread(mod, context, source, target);
} else { }
thread = new DatabaseMigrationThread(mod, context, source, target); if (params.getFlags().contains("update") || params.getFlags().contains("u")) {
} thread.setMode(DatabaseMigrationThread.Mode.UPDATE);
if (params.getFlags().contains("update") || params.getFlags().contains("u")) { }
thread.setMode(DatabaseMigrationThread.Mode.UPDATE); if (params.getFlags().contains("debug") || params.getFlags().contains("d")) {
} thread.setDebug(true);
if (params.getFlags().contains("debug") || params.getFlags().contains("d")) { }
thread.setDebug(true);
} if (!params.getFlags().contains("confirm")) {
context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.migrate_confirm", "--confirm"));
if (!params.getFlags().contains("confirm")) { return true;
context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.migrate_confirm", "--confirm")); }
return true;
} mod.getModuleEntry().disable();
mod.getModuleEntry().disable(); thread.start();
String sourceType = source.getType().toString();
thread.start(); if (params.getParameter("import") != null) {
String sourceType = source.getType().toString(); if (params.getParameter("import").equals("cc")) {
if (params.getParameter("import") != null) { sourceType = "CreativeControl-" + sourceType;
if (params.getParameter("import").equals("cc")) { }
sourceType = "CreativeControl-" + sourceType; }
} context.response(L("command.blockstate.migrate_started", sourceType, target.getType()));
} return true;
context.response(L("command.blockstate.migrate_started", sourceType, target.getType())); }
return true;
} private String L(String msg, Object... args) {
return mod.getPlugin().getLocale().trans(msg, args);
private String L(String msg, Object... args) { }
return mod.getPlugin().getLocale().trans(msg, args); }
}
}

View file

@ -131,7 +131,7 @@ public class CreativeControlImportThread extends DatabaseMigrationThread {
bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z"))); bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z")));
bs.setDate(new Date(rs.getLong("time"))); bs.setDate(new Date(rs.getLong("time")));
bs.setGameMode(GameMode.CREATIVE); bs.setGameMode(GameMode.CREATIVE);
bs.setPlayerName(rs.getString("player")); bs.setPlayerNameOrUUID(rs.getString("player"));
bs.setSource(Source.PLAYER); bs.setSource(Source.PLAYER);
return bs; return bs;
} }

View file

@ -42,7 +42,7 @@ public class DBQueries {
bs.setLocation(loc); bs.setLocation(loc);
bs.setDate(rs.getTimestamp("cdate")); bs.setDate(rs.getTimestamp("cdate"));
bs.setGameMode(getGameMode(rs)); bs.setGameMode(getGameMode(rs));
bs.setPlayerName(rs.getString("player")); bs.setPlayerNameOrUUID(rs.getString("player"));
bs.setSource(getSource(rs)); bs.setSource(getSource(rs));
rs.close(); rs.close();
return bs; return bs;
@ -72,7 +72,7 @@ public class DBQueries {
bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z"))); bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z")));
bs.setDate(rs.getTimestamp("cdate")); bs.setDate(rs.getTimestamp("cdate"));
bs.setGameMode(getGameMode(rs)); bs.setGameMode(getGameMode(rs));
bs.setPlayerName(rs.getString("player")); bs.setPlayerNameOrUUID(rs.getString("player"));
bs.setSource(getSource(rs)); bs.setSource(getSource(rs));
blocks.add(bs); blocks.add(bs);
} }
@ -100,7 +100,7 @@ public class DBQueries {
bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z"))); bs.setLocation(new Location(c.getWorld(), rs.getInt("x"), rs.getInt("y"), rs.getInt("z")));
bs.setDate(rs.getTimestamp("cdate")); bs.setDate(rs.getTimestamp("cdate"));
bs.setGameMode(getGameMode(rs)); bs.setGameMode(getGameMode(rs));
bs.setPlayerName(rs.getString("player")); bs.setPlayerNameOrUUID(rs.getString("player"));
bs.setSource(getSource(rs)); bs.setSource(getSource(rs));
return bs; return bs;
} }
@ -138,7 +138,7 @@ public class DBQueries {
update.setString(1, s.getGameMode().name()); update.setString(1, s.getGameMode().name());
else else
update.setInt(1, s.getGameMode().getValue()); update.setInt(1, s.getGameMode().getValue());
update.setString(2, s.getPlayerName()); update.setString(2, s.getPlayerUUID().toString());
update.setTimestamp(3, new java.sql.Timestamp(s.getDate().getTime())); update.setTimestamp(3, new java.sql.Timestamp(s.getDate().getTime()));
if (db.getType() == Type.MySQL) if (db.getType() == Type.MySQL)
update.setString(4, s.getSource().name()); update.setString(4, s.getSource().name());
@ -207,7 +207,7 @@ public class DBQueries {
insert.setString(5, s.getGameMode().name()); insert.setString(5, s.getGameMode().name());
else else
insert.setInt(5, s.getGameMode().getValue()); insert.setInt(5, s.getGameMode().getValue());
insert.setString(6, s.getPlayerName()); insert.setString(6, s.getPlayerUUID().toString());
insert.setTimestamp(7, new java.sql.Timestamp(s.getDate().getTime())); insert.setTimestamp(7, new java.sql.Timestamp(s.getDate().getTime()));
if (db.getType() == Type.MySQL) if (db.getType() == Type.MySQL)
insert.setString(8, s.getSource().name()); insert.setString(8, s.getSource().name());

View file

@ -11,7 +11,6 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.hanging.HangingBreakEvent; import org.bukkit.event.hanging.HangingBreakEvent;

View file

@ -29,7 +29,7 @@ public class PlayerListener implements Listener {
public void onInteract(PlayerInteractEvent event) { public void onInteract(PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Block b = event.getClickedBlock(); Block b = event.getClickedBlock();
if (b != null && event.getPlayer().getItemInHand().getType().equals(mod.getConfig().getTool()) && mod.getPlugin().getPermManager().hasPermission(event.getPlayer(), BlockStatePermissions.TOOL)) { if (b != null && event.getPlayer().getInventory().getItemInMainHand().getType().equals(mod.getConfig().getTool()) && mod.getPlugin().getPermManager().hasPermission(event.getPlayer(), BlockStatePermissions.TOOL)) {
if (mod.getConfig().getIgnoredWorlds().contains(event.getClickedBlock().getWorld().getName())) { if (mod.getConfig().getIgnoredWorlds().contains(event.getClickedBlock().getWorld().getName())) {
event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("command.blockstate.world_ignored", event.getClickedBlock().getWorld().getName())); event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("command.blockstate.world_ignored", event.getClickedBlock().getWorld().getName()));
} else { } else {
@ -41,7 +41,7 @@ public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onInteractEntity(PlayerInteractEntityEvent event) { public void onInteractEntity(PlayerInteractEntityEvent event) {
Entity e = event.getRightClicked(); Entity e = event.getRightClicked();
if (e != null && e instanceof ItemFrame && event.getPlayer().getItemInHand().getType().equals(mod.getConfig().getTool()) && mod.getPlugin().getPermManager().hasPermission(event.getPlayer(), BlockStatePermissions.TOOL)) { if (e != null && e instanceof ItemFrame && event.getPlayer().getInventory().getItemInMainHand().getType().equals(mod.getConfig().getTool()) && mod.getPlugin().getPermManager().hasPermission(event.getPlayer(), BlockStatePermissions.TOOL)) {
if (mod.getConfig().getIgnoredWorlds().contains(e.getWorld().getName())) { if (mod.getConfig().getIgnoredWorlds().contains(e.getWorld().getName())) {
event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("command.blockstate.world_ignored", e.getWorld().getName())); event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("command.blockstate.world_ignored", e.getWorld().getName()));
} else { } else {

View file

@ -1,22 +1,21 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate.thread; package de.jaschastarke.minecraft.limitedcreative.blockstate.thread;
import de.jaschastarke.bukkit.lib.ModuleLogger;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
import de.jaschastarke.minecraft.limitedcreative.blockstate.AbstractModel.HasBlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBQueries;
import de.jaschastarke.minecraft.limitedcreative.blockstate.ThreadedModel;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.block.Block;
import java.lang.Thread.UncaughtExceptionHandler; import java.lang.Thread.UncaughtExceptionHandler;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.block.Block;
import de.jaschastarke.bukkit.lib.ModuleLogger;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.AbstractModel.HasBlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBQueries;
import de.jaschastarke.minecraft.limitedcreative.blockstate.ThreadedModel;
public class ThreadLink { public class ThreadLink {
private static final int BATCH_ACTION_LENGTH = 25; private static final int BATCH_ACTION_LENGTH = 25;
private static final int QUEUE_ACCESS_WARNING_DURATION = 5; // ms private static final int QUEUE_ACCESS_WARNING_DURATION = 5; // ms
@ -24,10 +23,11 @@ public class ThreadLink {
private static final int COUNT_ERROR_QUEUE = 20; private static final int COUNT_ERROR_QUEUE = 20;
private static final int QUEUE_TIMING_DURATION = 500; // ms private static final int QUEUE_TIMING_DURATION = 500; // ms
private static final int STARTUP_TIMING = 30000; // ms private static final int STARTUP_TIMING = 30000; // ms
private static final int THREAD_SHUTDOWN_WAIT_MS = 30000;
private long lastTimeout; private long lastTimeout;
private Stack<Action> updateQueue = new Stack<Action>(); private final Stack<Action> updateQueue = new Stack<Action>();
private boolean shutdown = false; private boolean shutdown;
private ModuleLogger log; private ModuleLogger log;
private ThreadedModel model; private ThreadedModel model;
private Thread thread; private Thread thread;
@ -39,15 +39,8 @@ public class ThreadLink {
/* /*
* In theory we could add multiple threads, e.g. 1 write and 2 read threads. * In theory we could add multiple threads, e.g. 1 write and 2 read threads.
*/ */
thread = new DBThread(queries); createThread(queries);
thread.setName("LC BlockState DB-Thread"); shutdown = true; //Don't allow the thread to run until it's started
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable e) {
e.printStackTrace();
log.severe("Thread " + thread.getName() + " encoutered an uncaught Exception: " + e.getMessage());
}
});
} }
private class DBThread extends Thread { private class DBThread extends Thread {
@ -62,6 +55,8 @@ public class ThreadLink {
lastTimeout = System.currentTimeMillis() + STARTUP_TIMING; lastTimeout = System.currentTimeMillis() + STARTUP_TIMING;
while (!shutdown || !updateQueue.isEmpty()) { while (!shutdown || !updateQueue.isEmpty()) {
try { try {
//Thread.sleep(1000);
//throw new RuntimeException("Test exception pls ignore");
List<Action> acts = new LinkedList<Action>(); List<Action> acts = new LinkedList<Action>();
synchronized (updateQueue) { synchronized (updateQueue) {
while (updateQueue.isEmpty() && !shutdown) while (updateQueue.isEmpty() && !shutdown)
@ -91,6 +86,7 @@ public class ThreadLink {
for (Action act : acts) { for (Action act : acts) {
if (!shutdown || !(act instanceof CacheChunkAction)) { if (!shutdown || !(act instanceof CacheChunkAction)) {
if (act instanceof CallableAction) { if (act instanceof CallableAction) {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (act) { synchronized (act) {
act.process(ThreadLink.this, this.q); act.process(ThreadLink.this, this.q);
act.notify(); act.notify();
@ -104,7 +100,7 @@ public class ThreadLink {
log.debug("DB-Thread '" + Thread.currentThread().getName() + "' execution time: " + (System.currentTimeMillis() - t) + "ms"); log.debug("DB-Thread '" + Thread.currentThread().getName() + "' execution time: " + (System.currentTimeMillis() - t) + "ms");
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
log.severe("DB-Thread '" + Thread.currentThread().getName() + "' was harmfull interupted"); log.severe("DB-Thread '" + Thread.currentThread().getName() + "' was harmfully interupted");
} }
Thread.yield(); Thread.yield();
} }
@ -112,44 +108,49 @@ public class ThreadLink {
log.debug("DB-Thread " + Thread.currentThread().getName() + " finished."); log.debug("DB-Thread " + Thread.currentThread().getName() + " finished.");
} }
} }
public void start() { public void start() {
shutdown = false;
if (!thread.isAlive()) if (!thread.isAlive())
thread.start(); thread.start();
} }
public void queueUpdate(Block block) { public void queueUpdate(Block block) {
restartThreadIfNeeded();
long l = System.currentTimeMillis(); long l = System.currentTimeMillis();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(new UpdateBlockStateAction(block)); updateQueue.add(new UpdateBlockStateAction(block));
updateQueue.notify(); updateQueue.notifyAll();
} }
long l2 = System.currentTimeMillis(); long l2 = System.currentTimeMillis();
if (l2 - l > QUEUE_ACCESS_WARNING_DURATION) { if (l2 - l > QUEUE_ACCESS_WARNING_DURATION) {
getLog().warn("queueUpdate-action took to long: " + (l - 2) + "ms"); getLog().warn("queueUpdate-action took too long: " + (l2 - l) + "ms");
} }
} }
public BlockState callUpdate(Block block) { public BlockState callUpdate(Block block) {
restartThreadIfNeeded();
FetchBlockStateAction action = new FetchBlockStateAction(block); FetchBlockStateAction action = new FetchBlockStateAction(block);
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.push(action); updateQueue.push(action);
updateQueue.notify(); updateQueue.notifyAll();
} }
return action.getValue(); return action.getValue();
} }
public void queue(Action act) { public void queue(Action act) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(act); updateQueue.add(act);
updateQueue.notify(); updateQueue.notifyAll();
} }
} }
public <T> T call(CallableAction<T> act) { public <T> T call(CallableAction<T> act) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.push(act); updateQueue.push(act);
updateQueue.notify(); updateQueue.notifyAll();
} }
return act.getValue(); return act.getValue();
} }
@ -158,38 +159,43 @@ public class ThreadLink {
FetchCuboidAction action = new FetchCuboidAction(c); FetchCuboidAction action = new FetchCuboidAction(c);
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.push(action); updateQueue.push(action);
updateQueue.notify(); updateQueue.notifyAll();
} }
return action.getValue(); return action.getValue();
} }
public void queueMetaMove(Location from, Location to) { public void queueMetaMove(Location from, Location to) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(new MoveBlockStateAction(from, to)); updateQueue.add(new MoveBlockStateAction(from, to));
updateQueue.notify(); updateQueue.notifyAll();
} }
} }
public void queueChunkLoad(Chunk chunk) { public void queueChunkLoad(Chunk chunk) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(new CacheChunkAction(chunk)); updateQueue.add(new CacheChunkAction(chunk));
updateQueue.notify(); updateQueue.notifyAll();
} }
} }
public void queueTransaction(Transaction transaction) { public void queueTransaction(Transaction transaction) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(transaction); updateQueue.add(transaction);
updateQueue.notify(); updateQueue.notifyAll();
} }
} }
public void shutdown() throws InterruptedException { public void shutdown() throws InterruptedException {
synchronized (updateQueue) { synchronized (updateQueue) {
shutdown = true; shutdown = true;
updateQueue.notify(); updateQueue.notifyAll();
} }
thread.join(); thread.join(THREAD_SHUTDOWN_WAIT_MS);
if (thread.isAlive())
thread.interrupt(); //Wake it up
} }
public HasBlockState getMetaState(Block block) { public HasBlockState getMetaState(Block block) {
@ -209,4 +215,27 @@ public class ThreadLink {
public ModuleLogger getLog() { public ModuleLogger getLog() {
return log; return log;
} }
private void restartThreadIfNeeded() {
if ((thread != null && thread.isAlive()) || shutdown)
return;
log.warn("Thread is dead, restarting!");
new Exception("Thread-restarting update called").printStackTrace();
createThread(((DBThread) thread).q);
start();
}
private void createThread(DBQueries queries) {
if (shutdown)
return;
thread = new DBThread(queries);
thread.setName("LC BlockState DB-Thread");
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable e) {
e.printStackTrace();
log.severe("Thread " + thread.getName() + " encoutered an uncaught Exception: " + e.getMessage());
}
});
}
} }

View file

@ -1,25 +1,24 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate.worldedit; package de.jaschastarke.minecraft.limitedcreative.blockstate.worldedit;
import java.util.Date; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.sk89q.worldedit.Vector; import java.util.Date;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates; public class EditSessionExtent extends AbstractDelegateExtent {
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source;
public class EditSessionExtent extends AbstractLoggingExtent {
private ModBlockStates mod; private ModBlockStates mod;
private Player player = null; private Player player = null;
private World world; private World world;
public EditSessionExtent(Extent extent, ModBlockStates mod, Player player, World world) { public EditSessionExtent(Extent extent, ModBlockStates mod, Player player, World world) {
super(extent); super(extent);
this.mod = mod; this.mod = mod;
@ -30,14 +29,15 @@ public class EditSessionExtent extends AbstractLoggingExtent {
/** /**
* Called when a block is being changed. * Called when a block is being changed.
* *
* @param position the position * @param pt the position
* @param newBlock the new block to replace the old one * @param newBlock the new block to replace the old one
*/ */
protected void onBlockChange(Vector pt, BaseBlock newBlock) { @Override
public <T extends BlockStateHolder<T>> boolean setBlock(BlockVector3 pt, T newBlock) throws WorldEditException {
if (mod.isDebug()) if (mod.isDebug())
mod.getLog().debug("WorldEdit-Integration: BlockChange: "+pt.toString()+" BB: " + newBlock.toString()); mod.getLog().debug("WorldEdit-Integration: BlockChange: " + pt.toString() + " BB: " + newBlock.toString());
Location loc = new Location(world, pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()); Location loc = new Location(world, pt.getBlockX(), pt.getBlockY(), pt.getBlockZ());
if (newBlock.getType() == 0) { if (newBlock.getBlockType().getMaterial().isAir()) {
mod.getModel().removeState(loc.getBlock()); mod.getModel().removeState(loc.getBlock());
} else { } else {
BlockState s = mod.getModel().getState(loc.getBlock()); BlockState s = mod.getModel().getState(loc.getBlock());
@ -46,13 +46,15 @@ public class EditSessionExtent extends AbstractLoggingExtent {
s.setLocation(loc); s.setLocation(loc);
} }
s.setGameMode(null); s.setGameMode(null);
s.setPlayerName(player.getName()); s.setPlayerNameOrUUID(player.getUniqueId().toString());
s.setDate(new Date()); s.setDate(new Date());
s.setSource(Source.EDIT); s.setSource(Source.EDIT);
if (mod.isDebug()) if (mod.isDebug())
mod.getLog().debug("WorldEdit-Integration: Saving BlockState: " + s.toString()); mod.getLog().debug("WorldEdit-Integration: Saving BlockState: " + s.toString());
mod.getModel().setState(s); mod.getModel().setState(s);
} }
super.setBlock(pt, newBlock);
return true;
} }
} }

View file

@ -1,18 +1,17 @@
package de.jaschastarke.minecraft.limitedcreative.hooks; package de.jaschastarke.minecraft.limitedcreative.hooks;
import org.bukkit.entity.Player;
import uk.org.whoami.authme.api.API;
import de.jaschastarke.minecraft.limitedcreative.Hooks; import de.jaschastarke.minecraft.limitedcreative.Hooks;
import de.jaschastarke.minecraft.limitedcreative.LimitedCreative; import de.jaschastarke.minecraft.limitedcreative.LimitedCreative;
import fr.xephi.authme.api.v3.AuthMeApi;
import org.bukkit.entity.Player;
@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime //@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime
public class AuthMeHooks { public class AuthMeHooks {
public AuthMeHooks(final LimitedCreative plugin) { public AuthMeHooks(final LimitedCreative plugin) {
Hooks.IsLoggedIn.register(new PlayerCheckHooker.Check() { Hooks.IsLoggedIn.register(new PlayerCheckHooker.Check() {
@Override @Override
public boolean test(Player player) { public boolean test(Player player) {
boolean li = API.isAuthenticated(player); boolean li = AuthMeApi.getInstance().isAuthenticated(player);
if (plugin.isDebug()) // not nessesary, but so no string concation without debug needed if (plugin.isDebug()) // not nessesary, but so no string concation without debug needed
plugin.getLog().debug("AuthMe: "+player.getName()+": logged in: "+li); plugin.getLog().debug("AuthMe: "+player.getName()+": logged in: "+li);
return li; return li;

View file

@ -1,16 +1,15 @@
package de.jaschastarke.minecraft.limitedcreative.inventories; package de.jaschastarke.minecraft.limitedcreative.inventories;
import de.jaschastarke.bukkit.lib.SimpleModule;
import de.jaschastarke.minecraft.limitedcreative.LimitedCreative;
import de.jaschastarke.minecraft.limitedcreative.ModInventories;
import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.events.RestoreInventoryEvent;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import uk.org.whoami.authme.events.RestoreInventoryEvent; //@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime
import uk.org.whoami.authme.events.StoreInventoryEvent;
import de.jaschastarke.bukkit.lib.SimpleModule;
import de.jaschastarke.minecraft.limitedcreative.LimitedCreative;
import de.jaschastarke.minecraft.limitedcreative.ModInventories;
@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime
public class AuthMeInventories extends SimpleModule<LimitedCreative> implements Listener { public class AuthMeInventories extends SimpleModule<LimitedCreative> implements Listener {
ModInventories invmod; ModInventories invmod;
public AuthMeInventories(LimitedCreative plugin, ModInventories modInventories) { public AuthMeInventories(LimitedCreative plugin, ModInventories modInventories) {
@ -19,16 +18,16 @@ public class AuthMeInventories extends SimpleModule<LimitedCreative> implements
} }
@EventHandler @EventHandler
public void onStoreInventory(StoreInventoryEvent event) { public void onStoreInventory(ProtectInventoryEvent event) {
if (isDebug()) if (isDebug())
getLog().debug("AuthMe Store Event: "+event.getPlayer().getName()); getLog().debug("AuthMe Store Event: " + event.getPlayer().getName());
event.getPlayer().closeInventory(); event.getPlayer().closeInventory();
GameMode cgm = event.getPlayer().getGameMode(); GameMode cgm = event.getPlayer().getGameMode();
if (cgm == GameMode.ADVENTURE && !invmod.getConfig().getSeparateAdventure()) if (cgm == GameMode.ADVENTURE && !invmod.getConfig().getSeparateAdventure())
cgm = GameMode.SURVIVAL; cgm = GameMode.SURVIVAL;
if (cgm != GameMode.CREATIVE || invmod.getConfig().getStoreCreative()) { if (cgm != GameMode.CREATIVE || invmod.getConfig().getStoreCreative()) {
invmod.getInventory(event.getPlayer()).save(cgm); invmod.getInventory(event.getPlayer()).save(cgm);
} }

View file

@ -47,7 +47,7 @@ public class Fallback {
@Override @Override
public void store(ConfigurationSection section) { public void store(ConfigurationSection section) {
for (int i = 0; i < inv.getSize(); i++) { for (int i = 0; i < inv.getSize(); i++) {
if (inv.getItem(i) != null && inv.getItem(i).getTypeId() != 0) if (inv.getItem(i) != null && !inv.getItem(i).getType().equals(Material.AIR))
sectionSetItem(section, String.valueOf(i), inv.getItem(i)); sectionSetItem(section, String.valueOf(i), inv.getItem(i));
} }
} }
@ -97,7 +97,7 @@ public class Fallback {
public static Map<Integer, ItemStack> storeInventory(PlayerInventory inv) { public static Map<Integer, ItemStack> storeInventory(PlayerInventory inv) {
Map<Integer, ItemStack> map = new HashMap<Integer, ItemStack>(); Map<Integer, ItemStack> map = new HashMap<Integer, ItemStack>();
for (int i = 0; i < inv.getSize(); i++) { for (int i = 0; i < inv.getSize(); i++) {
if (inv.getItem(i) != null && inv.getItem(i).getTypeId() != 0) { if (inv.getItem(i) != null && !inv.getItem(i).getType().equals(Material.AIR)) {
map.put(i, inv.getItem(i)); map.put(i, inv.getItem(i));
} }
} }
@ -133,13 +133,13 @@ public class Fallback {
@Override @Override
public void store(ConfigurationSection section) { public void store(ConfigurationSection section) {
if (inv.getHelmet() != null && inv.getHelmet().getTypeId() != 0) if (inv.getHelmet() != null && !inv.getHelmet().getType().equals(Material.AIR))
Items.sectionSetItem(section, "helmet", inv.getHelmet()); Items.sectionSetItem(section, "helmet", inv.getHelmet());
if (inv.getChestplate() != null && inv.getChestplate().getTypeId() != 0) if (inv.getChestplate() != null && !inv.getChestplate().getType().equals(Material.AIR))
Items.sectionSetItem(section, "chestplate", inv.getChestplate()); Items.sectionSetItem(section, "chestplate", inv.getChestplate());
if (inv.getLeggings() != null && inv.getLeggings().getTypeId() != 0) if (inv.getLeggings() != null && !inv.getLeggings().getType().equals(Material.AIR))
Items.sectionSetItem(section, "leggins", inv.getLeggings()); Items.sectionSetItem(section, "leggins", inv.getLeggings());
if (inv.getBoots() != null && inv.getBoots().getTypeId() != 0) if (inv.getBoots() != null && !inv.getBoots().getType().equals(Material.AIR))
Items.sectionSetItem(section, "boots", inv.getBoots()); Items.sectionSetItem(section, "boots", inv.getBoots());
} }

View file

@ -43,7 +43,7 @@ public class InvYamlStorage extends InvConfStorage {
@Override @Override
public void load(Inventory pinv, Target target) { public void load(Inventory pinv, Target target) {
load(pinv, YamlConfiguration.loadConfiguration(getFile(pinv, target))); load(pinv, YamlConfiguration.loadConfiguration(getFile(pinv, target, false)));
} }
@Override @Override
@ -52,7 +52,11 @@ public class InvYamlStorage extends InvConfStorage {
yml.options().header("DO NOT MODIFY THIS FILE"); yml.options().header("DO NOT MODIFY THIS FILE");
store(pinv, yml); store(pinv, yml);
try { try {
yml.save(getFile(pinv, target)); File nameFile=getFile(pinv, target, false);
File uuidFile=getFile(pinv, target, true);
if(!nameFile.equals(uuidFile)) //It'd be recreated right after, still, don't remove if the same
nameFile.delete(); //Delete file with name so it doesn't get loaded again
yml.save(uuidFile);
} catch (IOException e) { } catch (IOException e) {
mod.getLog().warn("Failed to save Inventory for Player " + pinv.getPlayer().getName()); mod.getLog().warn("Failed to save Inventory for Player " + pinv.getPlayer().getName());
e.printStackTrace(); e.printStackTrace();
@ -61,19 +65,28 @@ public class InvYamlStorage extends InvConfStorage {
@Override @Override
public void remove(Inventory pinv, Target target) { public void remove(Inventory pinv, Target target) {
getFile(pinv, target).delete(); getFile(pinv, target, true).delete();
} }
@Override @Override
public boolean contains(Inventory pinv, Target target) { public boolean contains(Inventory pinv, Target target) {
return getFile(pinv, target).exists(); return getFile(pinv, target, false).exists();
} }
protected File getFile(Inventory pinv, Target target) { protected File getFile(Inventory pinv, Target target, boolean uuidonly) {
if (target != default_target) { File file;
return new File(dir, pinv.getPlayer().getName() + "_" + target.toString().toLowerCase() + SUFFIX); String player;
} else { do {
return new File(dir, pinv.getPlayer().getName() + SUFFIX); player = uuidonly ? pinv.getPlayer().getUniqueId().toString() : pinv.getPlayer().getName();
} if (target != default_target) {
file = new File(dir, player + "_" + target.toString().toLowerCase() + SUFFIX);
} else {
file = new File(dir, player + SUFFIX);
}
if(uuidonly)
return file; //Use file with UUID, even if doesn't exist
uuidonly = true; //Run again with UUID, then return...
} while(!file.exists()); //...if the file with name is not found
return file; //Found file with player name
} }
} }

View file

@ -0,0 +1,217 @@
package de.jaschastarke.minecraft.limitedcreative.inventories.store;
import de.jaschastarke.bukkit.lib.CoreModule;
import de.jaschastarke.bukkit.lib.ModuleLogger;
import de.jaschastarke.minecraft.limitedcreative.inventories.Inventory;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ReflectionStorage extends PlayerInventoryStorage {
private CoreModule<?> mod;
private File dir;
private String nms;
private InvYamlStorage yamlStorage;
public ReflectionStorage(CoreModule<?> mod, File file) {
this.mod = mod;
dir = file;
yamlStorage = new InvYamlStorage(mod, file);
}
@Override
public ModuleLogger getLog() {
return mod.getLog();
}
private File getFile(UUID uuid) {
return new File(dir, uuid.toString() + "_ref.yml");
}
private Object getInventory(Player player) throws Exception {
org.bukkit.inventory.Inventory inv = player.getInventory();
if (getInventory == null)
getInventory = inv.getClass().getMethod("getInventory");
Object handle = getInventory.invoke(inv);
if (nms == null)
nms = handle.getClass().getPackage().getName();
return handle;
}
@Override
public void store(Inventory pinv, Inventory.Target target) {
try {
File f = getFile(pinv.getPlayer().getUniqueId());
YamlConfiguration config = YamlConfiguration.loadConfiguration(f);
config.set(target.name(), serialize(getInventory(pinv.getPlayer())));
config.save(f);
} catch (Exception e) {
e.printStackTrace();
}
}
private Method getInventory;
@Override
public void load(Inventory pinv, Inventory.Target target) {
Player player = pinv.getPlayer();
try {
File f = getFile(player.getUniqueId());
if (!f.exists()) { //If not found use the older file(s)
yamlStorage.load(pinv, target);
return;
}
//String content = new String(Files.readAllBytes(f.toPath()));
Configuration config = YamlConfiguration.loadConfiguration(f);
String content = config.getString(target.name());
if (content == null) {
yamlStorage.load(pinv, target);
return;
}
setFromSerialized(getInventory(player), content);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void remove(Inventory pinv, Inventory.Target target) {
File f = getFile(pinv.getPlayer().getUniqueId());
if (!f.exists()) return;
Configuration config = YamlConfiguration.loadConfiguration(f);
config.set(target.name(), null);
}
@Override
public boolean contains(Inventory pinv, Inventory.Target target) {
File f = getFile(pinv.getPlayer().getUniqueId());
if (!f.exists()) return yamlStorage.contains(pinv, target);
Configuration config = YamlConfiguration.loadConfiguration(f);
return config.contains(target.name()) || yamlStorage.contains(pinv, target);
}
//Based on iie's per-world inventory
//https://github.com/TBMCPlugins/iiePerWorldInventory/blob/master/src/buttondevteam/perworld/serializers/inventory.java
private Method save;
private Class<?> nbtcl;
private Method nbtcsta;
private Class<?> nbtcstcl;
//SERIALIZE ITEMSTACK
private String serializeItemStack(Object itemStack) throws Exception {
if (nbtcl == null)
nbtcl = Class.forName(nms + ".NBTTagCompound");
if (save == null)
save = itemStack.getClass().getMethod("save", nbtcl);
if (nbtcstcl == null)
nbtcstcl = Class.forName(nms + ".NBTCompressedStreamTools");
if (nbtcsta == null)
nbtcsta = nbtcstcl.getMethod("a", nbtcl, OutputStream.class);
Object tag = save.invoke(itemStack, nbtcl.newInstance());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
nbtcsta.invoke(null, tag, outputStream);
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
}
private Method nbtcstaa;
private Function<Object, Object> createStack;
//DESERIALIZE ITEMSTACK
private Object deserializeItemStack(String itemStackString) throws Exception {
if (nbtcstcl == null)
nbtcstcl = Class.forName(nms + ".NBTCompressedStreamTools");
if (nbtcstaa == null)
nbtcstaa = nbtcstcl.getMethod("a", InputStream.class);
if (nbtcl == null)
nbtcl = Class.forName(nms + ".NBTTagCompound");
try {
if (createStack == null) {
final Method a = iscl.getMethod("a", nbtcl);
createStack = nbt -> {
try {
return a.invoke(null, nbt);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
} catch (NoSuchMethodException ex) { //It can only get here inside the if
final Constructor<?> constructor = iscl.getConstructor(nbtcl);
createStack = nbt -> {
try {
return constructor.newInstance(nbt);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(itemStackString));
Object nbtTagCompound = nbtcstaa.invoke(null, inputStream);
return createStack.apply(nbtTagCompound);
}
private Method getSize;
private Method getItem;
//SERIALIZE INVENTORY
private String serialize(Object invInventory) throws Exception {
if (getSize == null)
getSize = invInventory.getClass().getMethod("getSize");
if (getItem == null)
getItem = invInventory.getClass().getMethod("getItem", int.class);
return IntStream.range(0, (int) getSize.invoke(invInventory))
.mapToObj(s -> {
try {
//nms ItemStack
Object i = getItem.invoke(invInventory, s);
return Objects.isNull(i) ? null : s + "#" + serializeItemStack(i);
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.joining(";"));
}
private Method clear;
private Method setItem;
private Class<?> iscl;
//SET INVENTORY FROM SERIALIZED
private void setFromSerialized(Object invInventory, String invString) throws Exception {
if (clear == null)
clear = invInventory.getClass().getMethod("clear");
if (iscl == null)
iscl = Class.forName(nms + ".ItemStack");
if (setItem == null)
setItem = invInventory.getClass().getMethod("setItem", int.class, iscl);
clear.invoke(invInventory); //clear inventory
if (invString != null && !invString.isEmpty())
Arrays.asList(invString.split(";"))
.parallelStream()
.forEach(s -> {
String[] e = s.split("#");
try {
setItem.invoke(invInventory, Integer.parseInt(e[0]), deserializeItemStack(e[1]));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
});
}
}

View file

@ -55,7 +55,7 @@ public class BlackList extends ArrayList<BlackList.Blacklisted> implements Confi
} }
public boolean matches(Block block) { public boolean matches(Block block) {
if (hasData) { if (hasData) {
return md.equals(new MaterialData(block.getType(), block.getData())); return md.equals(block.getState().getData());
} else { } else {
return block.getType().equals(md.getItemType()); return block.getType().equals(md.getItemType());
} }

View file

@ -52,7 +52,7 @@ public class BlackListEntity extends ArrayList<BlackListEntity.Blacklisted> impl
type = null; type = null;
} }
if (type == null) if (type == null)
type = EntityType.fromName(rep); type = EntityType.valueOf(rep);
try { try {
if (type == null) if (type == null)
type = EntityType.valueOf(rep); type = EntityType.valueOf(rep);

View file

@ -118,16 +118,16 @@ public class NoLimitPermissions extends SimplePermissionContainerNode {
return new InventoryPermission(CHEST, invtype); return new InventoryPermission(CHEST, invtype);
} }
public static IDynamicPermission INTERACT(Block block) { public static IDynamicPermission INTERACT(Block block) {
return new MaterialPermission(BASE_INTERACT, new MaterialData(block.getType(), block.getData())); return new MaterialPermission(BASE_INTERACT, block.getState().getData());
} }
public static IDynamicPermission USE(Block block) { public static IDynamicPermission USE(Block block) {
return new MaterialPermission(BASE_USE, new MaterialData(block.getType(), block.getData())); return new MaterialPermission(BASE_USE, block.getState().getData());
} }
public static IDynamicPermission USE(MaterialData m) { public static IDynamicPermission USE(MaterialData m) {
return new MaterialPermission(BASE_USE, m); return new MaterialPermission(BASE_USE, m);
} }
public static IDynamicPermission BREAK(Block block) { public static IDynamicPermission BREAK(Block block) {
return new MaterialPermission(BASE_BREAK, new MaterialData(block.getType(), block.getData())); return new MaterialPermission(BASE_BREAK, block.getState().getData());
} }

View file

@ -39,7 +39,6 @@ import org.bukkit.event.player.*;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.material.DirectionalContainer; import org.bukkit.material.DirectionalContainer;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import org.bukkit.projectiles.ProjectileSource;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission; import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import de.jaschastarke.minecraft.lib.permissions.IDynamicPermission; import de.jaschastarke.minecraft.lib.permissions.IDynamicPermission;
@ -195,8 +194,8 @@ public class PlayerListener implements Listener {
@EventHandler @EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!event.isCancelled() && event.getPlayer().getGameMode() == GameMode.CREATIVE) { if (!event.isCancelled() && event.getPlayer().getGameMode() == GameMode.CREATIVE) {
if (mod.getConfig().getBlockUse().isListed(event.getPlayer().getItemInHand())) { if (mod.getConfig().getBlockUse().isListed(event.getPlayer().getInventory().getItemInMainHand())) {
if (!checkPermission(event, NoLimitPermissions.USE(event.getPlayer().getItemInHand().getData()))) { if (!checkPermission(event, NoLimitPermissions.USE(event.getPlayer().getInventory().getItemInMainHand().getData()))) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("blocked.use")); event.getPlayer().sendMessage(mod.getPlugin().getLocale().trans("blocked.use"));
return; return;
@ -216,18 +215,15 @@ public class PlayerListener implements Listener {
public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) {
onPlayerInteractEntity(event); onPlayerInteractEntity(event);
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onEntityDamageByEntity(EntityDamageEvent rawevent) { public void onEntityDamageByEntity(EntityDamageEvent rawevent) {
if (rawevent instanceof EntityDamageByEntityEvent && !rawevent.isCancelled()) { if (rawevent instanceof EntityDamageByEntityEvent && !rawevent.isCancelled()) {
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) rawevent; EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) rawevent;
Entity source = event.getDamager(); Entity source = event.getDamager();
if (source instanceof Projectile) { if (source instanceof Projectile && ((Projectile) source).getShooter() instanceof Entity)
ProjectileSource shooter = ((Projectile) source).getShooter(); source = (Entity) ((Projectile) source).getShooter();
if (shooter instanceof Entity)
source = (Entity) shooter;
}
if (source instanceof Player) { if (source instanceof Player) {
Player player = (Player) source; Player player = (Player) source;

View file

@ -1,48 +1,47 @@
package de.jaschastarke.minecraft.limitedcreative.regions; package de.jaschastarke.minecraft.limitedcreative.regions;
import org.bukkit.GameMode; import com.sk89q.worldguard.protection.flags.Flag;
import org.bukkit.command.CommandSender; import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.Flag; import org.bukkit.GameMode;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup; /**
* Well, that was an interesting idea, but it doesn't work.
/** */
* Well, that was an interesting idea, but it doesn't work. public class GameModeFlag extends Flag<GameMode> {
*/ public GameModeFlag(String name, RegionGroup defaultGroup) {
public class GameModeFlag extends Flag<GameMode> { super(name, defaultGroup);
public GameModeFlag(String name, RegionGroup defaultGroup) { }
super(name, defaultGroup);
} @Override
public GameMode parseInput(FlagContext context) throws InvalidFlagFormat {
@Override String input = context.getUserInput();
public GameMode parseInput(WorldGuardPlugin plugin, CommandSender sender, String input) throws InvalidFlagFormat { input = input.trim();
input = input.trim(); if (input.equalsIgnoreCase("creative")) {
if (input.equalsIgnoreCase("creative")) { return GameMode.CREATIVE;
return GameMode.CREATIVE; } else if (input.equalsIgnoreCase("survival")) {
} else if (input.equalsIgnoreCase("survival")) { return GameMode.SURVIVAL;
return GameMode.SURVIVAL; } else if (input.equalsIgnoreCase("adventure")) {
} else if (input.equalsIgnoreCase("adventure")) { return GameMode.ADVENTURE;
return GameMode.ADVENTURE; } else if (input.equalsIgnoreCase("none")) {
} else if (input.equalsIgnoreCase("none")) { return null;
return null; } else {
} else { throw new InvalidFlagFormat("Expected survival/creative/none but got '" + input + "'");
throw new InvalidFlagFormat("Expected survival/creative/none but got '" + input + "'"); }
} }
}
@Override
@Override public GameMode unmarshal(Object o) {
public GameMode unmarshal(Object o) { GameMode gm = null;
GameMode gm = null; if (o != null) {
if (o != null) { gm = GameMode.valueOf((String) o);
gm = GameMode.valueOf((String) o); }
} return gm;
return gm; }
}
@Override
@Override public Object marshal(GameMode o) {
public Object marshal(GameMode o) { return o == null ? null : o.name();
return o == null ? null : o.name(); }
} }
}

View file

@ -1,282 +1,280 @@
package de.jaschastarke.minecraft.limitedcreative.regions; package de.jaschastarke.minecraft.limitedcreative.regions;
import java.util.ArrayList; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import java.util.List; import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.apache.commons.lang.StringUtils; import com.sk89q.worldguard.protection.ApplicableRegionSet;
import org.bukkit.Bukkit; import com.sk89q.worldguard.protection.flags.Flag;
import org.bukkit.ChatColor; import com.sk89q.worldguard.protection.flags.FlagContext;
import org.bukkit.World; import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat; import de.jaschastarke.LocaleString;
import com.sk89q.worldguard.protection.managers.RegionManager; import de.jaschastarke.bukkit.lib.chat.ChatFormattings;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import de.jaschastarke.bukkit.lib.commands.*;
import com.sk89q.worldguard.protection.regions.ProtectedRegion; import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand;
import de.jaschastarke.bukkit.lib.commands.annotations.Usages;
import de.jaschastarke.LocaleString; import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser;
import de.jaschastarke.bukkit.lib.chat.ChatFormattings; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion;
import de.jaschastarke.bukkit.lib.commands.BukkitCommand; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Completer;
import de.jaschastarke.bukkit.lib.commands.CommandContext; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Context;
import de.jaschastarke.bukkit.lib.commands.CommandException; import de.jaschastarke.maven.ArchiveDocComments;
import de.jaschastarke.bukkit.lib.commands.HelpCommand; import de.jaschastarke.maven.PluginCommand;
import de.jaschastarke.bukkit.lib.commands.ICommand; import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import de.jaschastarke.bukkit.lib.commands.IHelpDescribed; import de.jaschastarke.minecraft.limitedcreative.ModRegions;
import de.jaschastarke.bukkit.lib.commands.MethodCommand; import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagList;
import de.jaschastarke.bukkit.lib.commands.MissingPermissionCommandException; import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagValue;
import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand; import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.Region;
import de.jaschastarke.bukkit.lib.commands.annotations.Usages; import de.jaschastarke.modularize.ModuleEntry.ModuleState;
import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser; import org.apache.commons.lang.StringUtils;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion; import org.bukkit.Bukkit;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Completer; import org.bukkit.ChatColor;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Context; import org.bukkit.World;
import de.jaschastarke.maven.ArchiveDocComments;
import de.jaschastarke.maven.PluginCommand; import java.util.ArrayList;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission; import java.util.List;
import de.jaschastarke.minecraft.limitedcreative.ModRegions;
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagList; /**
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagValue; * LimitedCreative-Region-Command: configure creative regions
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.Region; * @usage /<command> - displays Regions-Command-Help
import de.jaschastarke.modularize.ModuleEntry.ModuleState; * @permission limitedcreative.region
*/
/** @ArchiveDocComments
* LimitedCreative-Region-Command: configure creative regions @PluginCommand
* @usage /<command> - displays Regions-Command-Help public class RegionsCommand extends BukkitCommand implements IHelpDescribed {
* @permission limitedcreative.region private final static String GLOBAL_REGION = "__global__";
*/ private ModRegions mod;
@ArchiveDocComments private HelpCommand help;
@PluginCommand private WorldGuardPlugin wg;
public class RegionsCommand extends BukkitCommand implements IHelpDescribed {
private final static String GLOBAL_REGION = "__global__"; public RegionsCommand() {
private ModRegions mod; this.help = this.getDefaultHelpCommand();
private HelpCommand help; }
private WorldGuardPlugin wg; public RegionsCommand(ModRegions mod) {
super(mod.getPlugin());
public RegionsCommand() { this.help = this.getDefaultHelpCommand();
this.help = this.getDefaultHelpCommand(); this.mod = mod;
} this.wg = (WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME);
public RegionsCommand(ModRegions mod) { fullfillTabCompletion();
super(mod.getPlugin()); }
this.help = this.getDefaultHelpCommand();
this.mod = mod; @Override
this.wg = (WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME); public String getName() {
fullfillTabCompletion(); return "lcr";
} }
@Override @Override
public String getName() { public String[] getAliases() {
return "lcr"; return new String[]{"/region"};
} }
@Override public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException {
public String[] getAliases() { if (mod.getModuleEntry().getState() != ModuleState.ENABLED)
return new String[]{"/region"}; throw new CommandException("Module " + mod.getName() + " is disabled");
} return super.execute(context, args);
}
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException {
if (mod.getModuleEntry().getState() != ModuleState.ENABLED) /**
throw new CommandException("Module " + mod.getName() + " is disabled"); * @internal has no effect, as not tested by any command handler
return super.execute(context, args); * @see IHelpDescribed
} */
@Override
/** public IAbstractPermission[] getRequiredPermissions() {
* @internal has no effect, as not tested by any command handler return new IAbstractPermission[]{RegionPermissions.REGION};
* @see IHelpDescribed }
*/ @Override
@Override public String[] getUsages() {
public IAbstractPermission[] getRequiredPermissions() { return null;
return new IAbstractPermission[]{RegionPermissions.REGION}; }
} @Override
@Override public CharSequence getDescription() {
public String[] getUsages() { return new LocaleString("command.regions");
return null; }
} @Override
@Override public String getPackageName() {
public CharSequence getDescription() { return mod.getPlugin().getName() + " - " + mod.getName();
return new LocaleString("command.regions"); }
}
@Override /*@Override
public String getPackageName() { public IPermission getPermission(String subPerm) {
return mod.getPlugin().getName() + " - " + mod.getName(); if (subPerm.equals("region"))
} return RegionPermissions.REGION;
else
/*@Override return RegionPermissions.REGION.getPermission(subPerm);
public IPermission getPermission(String subPerm) { }*/
if (subPerm.equals("region"))
return RegionPermissions.REGION; protected void fullfillTabCompletion() {
else for (ICommand cmd : handler.getCommands()) {
return RegionPermissions.REGION.getPermission(subPerm); if (cmd instanceof MethodCommand) {
}*/ if (cmd.getName().equals("info")) {
((MethodCommand) cmd).getCompleter().add(TabCompletion.forUsageLine("[region]"));
protected void fullfillTabCompletion() { }
for (ICommand cmd : handler.getCommands()) { for (TabCompletion c : ((MethodCommand) cmd).getCompleter()) {
if (cmd instanceof MethodCommand) { c.setCompleter("region", new RegionCompleter());
if (cmd.getName().equals("info")) { }
((MethodCommand) cmd).getCompleter().add(TabCompletion.forUsageLine("[region]")); }
} }
for (TabCompletion c : ((MethodCommand) cmd).getCompleter()) { }
c.setCompleter("region", new RegionCompleter());
} private class RegionCompleter implements Completer {
} @Override
} public List<String> get(Context context, String arg) {
} int idx = -1;
String[] args = context.getHelper().getArguments();
private class RegionCompleter implements Completer { for (int i = 0; i < args.length; i++) {
@Override if (args[i].equals("world")) {
public List<String> get(Context context, String arg) { idx = i;
int idx = -1; break;
String[] args = context.getHelper().getArguments(); }
for (int i = 0; i < args.length; i++) { }
if (args[i].equals("world")) { World w = context.getCommandContext().isPlayer() ? context.getCommandContext().getPlayer().getWorld() : null;
idx = i; if (idx > -1 && context.getArgument(idx) != null)
break; w = Bukkit.getWorld(context.getArgument(idx));
} if (w != null) {
} RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
World w = context.getCommandContext().isPlayer() ? context.getCommandContext().getPlayer().getWorld() : null; RegionManager mgr = container.get(BukkitAdapter.adapt(w));
if (idx > -1 && context.getArgument(idx) != null) if (mgr != null) {
w = Bukkit.getWorld(context.getArgument(idx)); List<String> hints = new ArrayList<String>();
if (w != null) { for (String rId : mgr.getRegions().keySet()) {
RegionManager mgr = getWorldGuard().getGlobalRegionManager().get(w); if (rId.toLowerCase().startsWith(arg.toLowerCase()))
if (mgr != null) { hints.add(rId);
List<String> hints = new ArrayList<String>(); }
for (String rId : mgr.getRegions().keySet()) { return hints;
if (rId.toLowerCase().startsWith(arg.toLowerCase())) }
hints.add(rId); }
} return null;
return hints; }
} }
}
return null; /**
} * Sets the Flag of a region to a new value. If no value given, the flag is removed.
} * -g sets the affected group of the flag, instead the flag (equivalent to using flag-group as flag-name)
* -w world uses a world by name instead the world your in (required from console)
/** */
* Sets the Flag of a region to a new value. If no value given, the flag is removed. @IsCommand("flag")
* -g sets the affected group of the flag, instead the flag (equivalent to using flag-group as flag-name) //@NeedsPermission("region") // not needed as the whole command requires permissions
* -w world uses a world by name instead the world your in (required from console) @Usages("<region> -g <flag> -w world [value]")
*/ public boolean setFlag(CommandContext context, String... args) throws CommandException, MissingPermissionCommandException {
@IsCommand("flag") DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"g"}, 2);
//@NeedsPermission("region") // not needed as the whole command requires permissions if (params.getArgumentCount() < 2) {// doesn't count parameters
@Usages("<region> -g <flag> -w world [value]") help.execute(context, new String[]{"flag"});
public boolean setFlag(CommandContext context, String... args) throws CommandException, MissingPermissionCommandException { context.response(L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender()));
DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"g"}, 2); return true;
if (params.getArgumentCount() < 2) {// doesn't count parameters }
help.execute(context, new String[]{"flag"});
context.response(L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender())); World w = context.isPlayer() ? context.getPlayer().getWorld() : null;
return true; if (params.getParameter("-w") != null)
} w = mod.getPlugin().getServer().getWorld(params.getParameter("-w"));
if (w == null)
World w = context.isPlayer() ? context.getPlayer().getWorld() : null; throw new CommandException(L("command.worldguard.world_not_found"));
if (params.getParameter("-w") != null)
w = mod.getPlugin().getServer().getWorld(params.getParameter("-w")); RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
if (w == null) RegionManager mgr = container.get(BukkitAdapter.adapt(w));
throw new CommandException(L("command.worldguard.world_not_found")); ProtectedRegion region = mgr.getRegion(params.getArgument(0));
if (region == null && params.getArgument(0).equalsIgnoreCase("__global__")) {
RegionManager mgr = getWorldGuard().getGlobalRegionManager().get(w); region = new GlobalProtectedRegion(params.getArgument(0));
ProtectedRegion region = mgr.getRegion(params.getArgument(0)); mgr.addRegion(region);
if (region == null && params.getArgument(0).equalsIgnoreCase("__global__")) { }
region = new GlobalProtectedRegion(params.getArgument(0)); if (region == null)
mgr.addRegion(region); throw new CommandException(L("command.worldguard.region_not_found"));
}
if (region == null) Region reg = mod.getRegionManager().world(w).region(region);
throw new CommandException(L("command.worldguard.region_not_found"));
Flag<?> flag = FlagList.getFlag(params.getArgument(1));
Region reg = mod.getRegionManager().world(w).region(region); if (flag == null) {
String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "\n"
Flag<?> flag = FlagList.getFlag(params.getArgument(1)); + L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender());
if (flag == null) { throw new CommandException(msg);
String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "\n" } else if (params.getFlags().contains("g")) {
+ L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender()); flag = flag.getRegionGroupFlag();
throw new CommandException(msg); if (flag == null) {
} else if (params.getFlags().contains("g")) { String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "-group\n"
flag = flag.getRegionGroupFlag(); + L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender());
if (flag == null) { throw new CommandException(msg);
String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "-group\n" }
+ L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender()); }
throw new CommandException(msg);
} String value = params.getValue();
} try {
if (value != null && value.trim().length() > 0) {
String value = params.getValue(); reg.setFlag(flag, flag.parseInput(FlagContext.create().setInput(value).build()));
try { } else {
if (value != null && value.trim().length() > 0) { reg.setFlag(flag, null);
reg.setFlag(flag, flag.parseInput(getWorldGuard(), context.getSender(), value)); }
} else { } catch (InvalidFlagFormat e) {
reg.setFlag(flag, null); context.response(context.getFormatter().formatString(ChatFormattings.ERROR, e.getLocalizedMessage()));
} return true;
} catch (InvalidFlagFormat e) { }
context.response(context.getFormatter().formatString(ChatFormattings.ERROR, e.getLocalizedMessage()));
return true; context.response(L("command.worldguard.flag_set", flag.getName()));
} return true;
}
context.response(L("command.worldguard.flag_set", flag.getName()));
return true; @IsCommand("info")
} //@NeedsPermission("region")
@Usages("[world] [region]")
@IsCommand("info") public boolean getInfo(CommandContext context, String... args) throws CommandException {
//@NeedsPermission("region") DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"s"}, 1);
@Usages("[world] [region]")
public boolean getInfo(CommandContext context, String... args) throws CommandException { if (context.isPlayer()) {
DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"s"}, 1); /*
* WorldEdits intercepting Servers privates commandMap via Reflections realy sucks!
if (context.isPlayer()) { * Just because they are to lazy to add all the lines commands to plugin.yml
/* */
* WorldEdits intercepting Servers privates commandMap via Reflections realy sucks! String orgCmd = ("region info " + StringUtils.join(args)).trim();
* Just because they are to lazy to add all the lines commands to plugin.yml mod.getPlugin().getServer().dispatchCommand(context.getSender(), orgCmd);
*/ }
String orgCmd = ("region info " + StringUtils.join(args)).trim();
mod.getPlugin().getServer().dispatchCommand(context.getSender(), orgCmd); World w = context.isPlayer() ? context.getPlayer().getWorld() : null;
} if (params.getArgumentCount() > 1)
w = mod.getPlugin().getServer().getWorld(params.getArgument(0));
World w = context.isPlayer() ? context.getPlayer().getWorld() : null; if (w == null)
if (params.getArgumentCount() > 1) throw new CommandException(L("command.worldguard.world_not_found"));
w = mod.getPlugin().getServer().getWorld(params.getArgument(0));
if (w == null) ProtectedRegion region = null;
throw new CommandException(L("command.worldguard.world_not_found")); RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
if (params.getArgumentCount() == 0 && context.isPlayer()) {
ProtectedRegion region = null; RegionManager mgr = container.get(BukkitAdapter.adapt(context.getPlayer().getWorld()));
if (params.getArgumentCount() == 0 && context.isPlayer()) { ApplicableRegionSet set = mgr.getApplicableRegions(BukkitAdapter.asBlockVector(context.getPlayer().getLocation()));
RegionManager mgr = getWorldGuard().getGlobalRegionManager().get(context.getPlayer().getWorld()); if (set.size() > 0) {
ApplicableRegionSet set = mgr.getApplicableRegions(context.getPlayer().getLocation()); region = set.iterator().next();
if (set.size() > 0) { } else {
region = set.iterator().next(); region = container.get(BukkitAdapter.adapt(w)).getRegion(GLOBAL_REGION);
} else { }
region = getWorldGuard().getGlobalRegionManager().get(w).getRegion(GLOBAL_REGION); } else {
} int rpc = params.getArgumentCount() > 1 ? 1 : 0;
} else { RegionManager mgr = container.get(BukkitAdapter.adapt(w));
int rpc = params.getArgumentCount() > 1 ? 1 : 0; region = mgr.getRegion(params.getArgument(rpc));
RegionManager mgr = getWorldGuard().getGlobalRegionManager().get(w); if (region == null && params.getArgument(rpc).equalsIgnoreCase(GLOBAL_REGION)) {
region = mgr.getRegion(params.getArgument(rpc)); region = new GlobalProtectedRegion(params.getArgument(rpc));
if (region == null && params.getArgument(rpc).equalsIgnoreCase(GLOBAL_REGION)) { mgr.addRegion(region);
region = new GlobalProtectedRegion(params.getArgument(rpc)); }
mgr.addRegion(region); }
} if (region == null)
} throw new CommandException(L("command.worldguard.region_not_found"));
if (region == null)
throw new CommandException(L("command.worldguard.region_not_found")); Region reg = mod.getRegionManager().world(w).region(region);
Region reg = mod.getRegionManager().world(w).region(region); StringBuilder list = new StringBuilder();
for (FlagValue data : reg.getFlags()) {
StringBuilder list = new StringBuilder(); if (list.length() > 0)
for (FlagValue data : reg.getFlags()) { list.append(", ");
if (list.length() > 0) list.append(data.getFlag().getName());
list.append(", "); list.append(": ");
list.append(data.getFlag().getName()); list.append(data.getValue().toString());
list.append(": "); }
list.append(data.getValue().toString());
} context.response(ChatColor.GREEN + L("command.worldguard.additional_flags") + list.toString());
return true;
context.response(ChatColor.GREEN + L("command.worldguard.additional_flags") + list.toString()); }
return true;
} private String L(String msg, Object... args) {
return mod.getPlugin().getLocale().trans(msg, args);
private String L(String msg, Object... args) { }
return mod.getPlugin().getLocale().trans(msg, args);
} private WorldGuardPlugin getWorldGuard() {
return wg;
private WorldGuardPlugin getWorldGuard() { }
return wg; }
}
}

View file

@ -22,6 +22,7 @@ import org.bukkit.entity.Player;
import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag; import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.StateFlag; import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class ApplicableRegions { public class ApplicableRegions {
@ -36,28 +37,28 @@ public class ApplicableRegions {
public boolean allows(StateFlag flag) { public boolean allows(StateFlag flag) {
extendRegionFlags(); extendRegionFlags();
boolean r = regions.allows(flag); boolean r = regions.queryState(null, flag).equals(State.ALLOW);
contractRegionFlags(); contractRegionFlags();
return r; return r;
} }
public boolean allows(StateFlag flag, Player player) { public boolean allows(StateFlag flag, Player player) {
extendRegionFlags(); extendRegionFlags();
boolean r = regions.allows(flag, mgr.getWorldGuard().wrapPlayer(player)); boolean r = regions.queryState(mgr.getWorldGuard().wrapPlayer(player), flag).equals(State.ALLOW);
contractRegionFlags(); contractRegionFlags();
return r; return r;
} }
public <T extends Flag<V>, V> V getFlag(T flag) { public <T extends Flag<V>, V> V getFlag(T flag) {
extendRegionFlags(); extendRegionFlags();
V r = regions.getFlag(flag); V r = regions.queryValue(null, flag);
contractRegionFlags(); contractRegionFlags();
return r; return r;
} }
public <T extends Flag<V>, V> V getFlag(T flag, Player player) { public <T extends Flag<V>, V> V getFlag(T flag, Player player) {
extendRegionFlags(); extendRegionFlags();
V r = regions.getFlag(flag, mgr.getWorldGuard().wrapPlayer(player)); V r = regions.queryValue(mgr.getWorldGuard().wrapPlayer(player), flag);
contractRegionFlags(); contractRegionFlags();
return r; return r;
} }

View file

@ -1,196 +1,189 @@
/* /*
* Limited Creative - (Bukkit Plugin) * Limited Creative - (Bukkit Plugin)
* Copyright (C) 2012 jascha@ja-s.de * Copyright (C) 2012 jascha@ja-s.de
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package de.jaschastarke.minecraft.limitedcreative.regions.worldguard; package de.jaschastarke.minecraft.limitedcreative.regions.worldguard;
import java.io.File; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import java.io.IOException; import com.sk89q.worldguard.WorldGuard;
import java.util.ArrayList; import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.util.Arrays; import com.sk89q.worldguard.protection.flags.Flag;
import java.util.HashMap; import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.List; import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import java.util.Map; import com.sk89q.worldguard.protection.regions.RegionContainer;
import de.jaschastarke.minecraft.limitedcreative.ModRegions;
import org.bukkit.Location; import de.jaschastarke.minecraft.limitedcreative.regions.WorldGuardIntegration;
import org.bukkit.World; import de.jaschastarke.utils.StringUtil;
import org.bukkit.block.Block; import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import com.sk89q.worldguard.bukkit.BukkitUtil; import org.bukkit.entity.Player;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.GlobalRegionManager; import java.io.File;
import com.sk89q.worldguard.protection.flags.Flag; import java.io.IOException;
import com.sk89q.worldguard.protection.managers.RegionManager; import java.util.*;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class CustomRegionManager {
import de.jaschastarke.minecraft.limitedcreative.ModRegions; protected YamlConfiguration c;
import de.jaschastarke.minecraft.limitedcreative.regions.WorldGuardIntegration; protected File file;
import de.jaschastarke.utils.StringUtil; private Map<World, CWorld> worlds = new HashMap<World, CWorld>();
private ModRegions mod;
public class CustomRegionManager { public CustomRegionManager(File file, ModRegions mod) {
protected YamlConfiguration c; this.file = file;
protected File file; this.mod = mod;
private Map<World, CWorld> worlds = new HashMap<World, CWorld>(); c = YamlConfiguration.loadConfiguration(file);
private ModRegions mod; }
public CustomRegionManager(File file, ModRegions mod) {
this.file = file;
this.mod = mod; public CWorld world(World w) {
c = YamlConfiguration.loadConfiguration(file); if (worlds.containsKey(w)) {
} return worlds.get(w);
} else {
CWorld r = new CWorld(w);
public CWorld world(World w) { worlds.put(w, r);
if (worlds.containsKey(w)) { return r;
return worlds.get(w); }
} else { }
CWorld r = new CWorld(w);
worlds.put(w, r); public class CWorld {
return r; private World world;
} private ConfigurationSection wc = null;
} public CWorld(World w) {
world = w;
public class CWorld { }
private World world; public CustomRegionManager getManager() {
private ConfigurationSection wc = null; return CustomRegionManager.this;
public CWorld(World w) { }
world = w; private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>();
} public Region region(ProtectedRegion pr) {
public CustomRegionManager getManager() { if (regions.containsKey(pr)) {
return CustomRegionManager.this; return regions.get(pr);
} } else {
private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>(); Region r = new Region(this, pr);
public Region region(ProtectedRegion pr) { regions.put(pr, r);
if (regions.containsKey(pr)) { return r;
return regions.get(pr); }
} else { }
Region r = new Region(this, pr); public World getWorld() {
regions.put(pr, r); return world;
return r; }
} public ProtectedRegion getGlobalRegion() {
} return getWGManager(world).getRegion("__global__");
public World getWorld() { }
return world;
} @SuppressWarnings("unchecked")
public ProtectedRegion getGlobalRegion() { public <V> void storeFlag(Region region, Flag<V> flag, Object value) {
return getWGManager(world).getRegion("__global__"); if (wc == null) {
} if (c.contains(world.getName().toLowerCase()))
wc = c.getConfigurationSection(world.getName().toLowerCase());
@SuppressWarnings("unchecked") else
public <V> void storeFlag(Region region, Flag<V> flag, Object value) { wc = c.createSection(world.getName().toLowerCase());
if (wc == null) { }
if (c.contains(world.getName().toLowerCase()))
wc = c.getConfigurationSection(world.getName().toLowerCase()); ConfigurationSection rs;
else if (wc.contains(region.getProtectedRegion().getId()))
wc = c.createSection(world.getName().toLowerCase()); rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
} else
rs = wc.createSection(region.getProtectedRegion().getId());
ConfigurationSection rs;
if (wc.contains(region.getProtectedRegion().getId())) ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags");
rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
else if (value == null) {
rs = wc.createSection(region.getProtectedRegion().getId()); fs.set(flag.getName(), null);
} else {
ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags"); fs.set(flag.getName(), flag.marshal((V) value));
}
if (value == null) {
fs.set(flag.getName(), null); try {
} else { c.save(file);
fs.set(flag.getName(), flag.marshal((V) value)); } catch (IOException e) {
} e.printStackTrace();
}
try { }
c.save(file); public List<FlagValue> getFlags(Region region) {
} catch (IOException e) { List<FlagValue> list = new ArrayList<FlagValue>();
e.printStackTrace();
} if (c.contains(world.getName().toLowerCase())) {
} ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase());
public List<FlagValue> getFlags(Region region) { if (wc.contains(region.getProtectedRegion().getId())) {
List<FlagValue> list = new ArrayList<FlagValue>(); ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
if (rs.contains("flags")) {
if (c.contains(world.getName().toLowerCase())) { ConfigurationSection fs = rs.getConfigurationSection("flags");
ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase()); for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) {
if (wc.contains(region.getProtectedRegion().getId())) { Flag<?> flag = null;
ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId()); if (data.getKey().endsWith("-group")) {
if (rs.contains("flags")) { flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6));
ConfigurationSection fs = rs.getConfigurationSection("flags"); if (flag != null)
for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) { flag = flag.getRegionGroupFlag();
Flag<?> flag = null; } else {
if (data.getKey().endsWith("-group")) { flag = FlagList.getFlag(data.getKey());
flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6)); }
if (flag != null) if (flag != null) { // the flag doesn't exists anymore. just ignore it without error
flag = flag.getRegionGroupFlag(); Object value = flag.unmarshal(data.getValue());
} else { list.add(new FlagValue(flag, value));
flag = FlagList.getFlag(data.getKey()); } else {
} if (mod.isDebug())
if (flag != null) { // the flag doesn't exists anymore. just ignore it without error mod.getLog().debug("Couldn't load unknown Flag: "+data.getKey());
Object value = flag.unmarshal(data.getValue()); }
list.add(new FlagValue(flag, value)); }
} else { }
if (mod.isDebug()) }
mod.getLog().debug("Couldn't load unknown Flag: "+data.getKey()); }
} return list;
} }
}
} public WorldGuardPlugin getWorldGuard() {
} return CustomRegionManager.this.getWorldGuard();
return list; }
} }
public WorldGuardPlugin getWorldGuard() { private WorldGuardPlugin getWorldGuard() {
return CustomRegionManager.this.getWorldGuard(); return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME));
} }
}
public RegionManager getWGManager(World world) {
private WorldGuardPlugin getWorldGuard() { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME)); return container.get(BukkitAdapter.adapt(world));
} }
public GlobalRegionManager getWGGlobalManager() { public String getRegionsHash(Location loc) {
return getWorldGuard().getGlobalRegionManager(); StringBuilder hash = new StringBuilder(loc.getWorld().getName());
} List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitAdapter.asBlockVector(loc));
public RegionManager getWGManager(World world) { if (idlist.size() > 0) {
return getWorldGuard().getRegionManager(world); hash.append("#");
} String[] ids = idlist.toArray(new String[idlist.size()]);
if (ids.length > 1) {
public String getRegionsHash(Location loc) { Arrays.sort(ids);
StringBuilder hash = new StringBuilder(loc.getWorld().getName()); }
List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(loc)); hash.append(StringUtil.join(ids, ","));
if (idlist.size() > 0) { }
hash.append("#"); return hash.toString();
String[] ids = idlist.toArray(new String[idlist.size()]); }
if (ids.length > 1) {
Arrays.sort(ids); public ApplicableRegions getRegionSet(Location loc) {
} return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(BukkitAdapter.asBlockVector(loc)), this.world(loc.getWorld()));
hash.append(StringUtil.join(ids, ",")); }
}
return hash.toString(); public ApplicableRegions getRegionSet(Block block) {
} return getRegionSet(block.getLocation());
}
public ApplicableRegions getRegionSet(Location loc) {
return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(loc), this.world(loc.getWorld())); public boolean isDiffrentRegion(Player player, Location loc) {
} return !getRegionsHash(loc).equals(mod.getPlayerData(player).getHash());
}
public ApplicableRegions getRegionSet(Block block) { }
return getRegionSet(block.getLocation());
}
public boolean isDiffrentRegion(Player player, Location loc) {
return !getRegionsHash(loc).equals(mod.getPlayerData(player).getHash());
}
}

View file

@ -17,7 +17,6 @@
*/ */
package de.jaschastarke.minecraft.limitedcreative.regions.worldguard.events; package de.jaschastarke.minecraft.limitedcreative.regions.worldguard.events;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
@ -25,11 +24,11 @@ import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.ApplicableRe
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.CustomRegionManager; import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.CustomRegionManager;
public class PlayerUpdateAreaEvent extends PlayerAreaEvent { public class PlayerUpdateAreaEvent extends PlayerAreaEvent {
private String player; private Player player;
private String hash; private String hash;
protected CustomRegionManager mgr; protected CustomRegionManager mgr;
public PlayerUpdateAreaEvent(CustomRegionManager mgr, String player, String hash) { public PlayerUpdateAreaEvent(CustomRegionManager mgr, Player player, String hash) {
this.mgr = mgr; this.mgr = mgr;
this.player = player; this.player = player;
this.hash = hash; this.hash = hash;
@ -46,7 +45,7 @@ public class PlayerUpdateAreaEvent extends PlayerAreaEvent {
@Override @Override
public Player getPlayer() { public Player getPlayer() {
return Bukkit.getServer().getPlayerExact(player); return player;
} }
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();

View file

@ -1,2 +0,0 @@
piwik_url = http://stats.ja-s.de/piwikProxy.php
piwik_site_id = 2