Compare commits

..

15 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
21 changed files with 1635 additions and 1366 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
```

570
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.9.4-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>R8-SNAPSHOT</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>2.1</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>
</project> <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>

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

@ -82,8 +82,14 @@ public class BlockState {
} }
//TODO Rename //TODO Rename
public void setPlayerName(String s) { @SuppressWarnings("deprecation")
uuid = UUID.fromString(s); 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() {
@ -115,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;
} }

View file

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

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.getUniqueId().toString()); 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

@ -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().getUniqueId() + "_" + target.toString().toLowerCase() + SUFFIX); String player;
} else { do {
return new File(dir, pinv.getPlayer().getUniqueId() + 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

@ -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;
@ -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().getRegionManager(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().getRegionManager(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().getRegionManager(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().getRegionManager(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().getRegionManager(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

@ -1,192 +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.flags.Flag; import java.io.File;
import com.sk89q.worldguard.protection.managers.RegionManager; import java.io.IOException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.*;
import de.jaschastarke.minecraft.limitedcreative.ModRegions; public class CustomRegionManager {
import de.jaschastarke.minecraft.limitedcreative.regions.WorldGuardIntegration; protected YamlConfiguration c;
import de.jaschastarke.utils.StringUtil; protected File file;
private Map<World, CWorld> worlds = new HashMap<World, CWorld>();
public class CustomRegionManager { private ModRegions mod;
protected YamlConfiguration c; public CustomRegionManager(File file, ModRegions mod) {
protected File file; this.file = file;
private Map<World, CWorld> worlds = new HashMap<World, CWorld>(); this.mod = mod;
private ModRegions mod; c = YamlConfiguration.loadConfiguration(file);
public CustomRegionManager(File file, ModRegions mod) { }
this.file = file;
this.mod = mod;
c = YamlConfiguration.loadConfiguration(file); public CWorld world(World w) {
} if (worlds.containsKey(w)) {
return worlds.get(w);
} else {
public CWorld world(World w) { CWorld r = new CWorld(w);
if (worlds.containsKey(w)) { worlds.put(w, r);
return worlds.get(w); return r;
} else { }
CWorld r = new CWorld(w); }
worlds.put(w, r);
return r; public class CWorld {
} private World world;
} private ConfigurationSection wc = null;
public CWorld(World w) {
public class CWorld { world = w;
private World world; }
private ConfigurationSection wc = null; public CustomRegionManager getManager() {
public CWorld(World w) { return CustomRegionManager.this;
world = w; }
} private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>();
public CustomRegionManager getManager() { public Region region(ProtectedRegion pr) {
return CustomRegionManager.this; if (regions.containsKey(pr)) {
} return regions.get(pr);
private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>(); } else {
public Region region(ProtectedRegion pr) { Region r = new Region(this, pr);
if (regions.containsKey(pr)) { regions.put(pr, r);
return regions.get(pr); return r;
} else { }
Region r = new Region(this, pr); }
regions.put(pr, r); public World getWorld() {
return r; return world;
} }
} public ProtectedRegion getGlobalRegion() {
public World getWorld() { return getWGManager(world).getRegion("__global__");
return world; }
}
public ProtectedRegion getGlobalRegion() { @SuppressWarnings("unchecked")
return getWGManager(world).getRegion("__global__"); public <V> void storeFlag(Region region, Flag<V> flag, Object value) {
} if (wc == null) {
if (c.contains(world.getName().toLowerCase()))
@SuppressWarnings("unchecked") wc = c.getConfigurationSection(world.getName().toLowerCase());
public <V> void storeFlag(Region region, Flag<V> flag, Object value) { else
if (wc == null) { wc = c.createSection(world.getName().toLowerCase());
if (c.contains(world.getName().toLowerCase())) }
wc = c.getConfigurationSection(world.getName().toLowerCase());
else ConfigurationSection rs;
wc = c.createSection(world.getName().toLowerCase()); if (wc.contains(region.getProtectedRegion().getId()))
} rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
else
ConfigurationSection rs; rs = wc.createSection(region.getProtectedRegion().getId());
if (wc.contains(region.getProtectedRegion().getId()))
rs = wc.getConfigurationSection(region.getProtectedRegion().getId()); ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags");
else
rs = wc.createSection(region.getProtectedRegion().getId()); if (value == null) {
fs.set(flag.getName(), null);
ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags"); } else {
fs.set(flag.getName(), flag.marshal((V) value));
if (value == null) { }
fs.set(flag.getName(), null);
} else { try {
fs.set(flag.getName(), flag.marshal((V) value)); c.save(file);
} } catch (IOException e) {
e.printStackTrace();
try { }
c.save(file); }
} catch (IOException e) { public List<FlagValue> getFlags(Region region) {
e.printStackTrace(); List<FlagValue> list = new ArrayList<FlagValue>();
}
} if (c.contains(world.getName().toLowerCase())) {
public List<FlagValue> getFlags(Region region) { ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase());
List<FlagValue> list = new ArrayList<FlagValue>(); if (wc.contains(region.getProtectedRegion().getId())) {
ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
if (c.contains(world.getName().toLowerCase())) { if (rs.contains("flags")) {
ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase()); ConfigurationSection fs = rs.getConfigurationSection("flags");
if (wc.contains(region.getProtectedRegion().getId())) { for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) {
ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId()); Flag<?> flag = null;
if (rs.contains("flags")) { if (data.getKey().endsWith("-group")) {
ConfigurationSection fs = rs.getConfigurationSection("flags"); flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6));
for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) { if (flag != null)
Flag<?> flag = null; flag = flag.getRegionGroupFlag();
if (data.getKey().endsWith("-group")) { } else {
flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6)); flag = FlagList.getFlag(data.getKey());
if (flag != null) }
flag = flag.getRegionGroupFlag(); if (flag != null) { // the flag doesn't exists anymore. just ignore it without error
} else { Object value = flag.unmarshal(data.getValue());
flag = FlagList.getFlag(data.getKey()); list.add(new FlagValue(flag, value));
} } else {
if (flag != null) { // the flag doesn't exists anymore. just ignore it without error if (mod.isDebug())
Object value = flag.unmarshal(data.getValue()); mod.getLog().debug("Couldn't load unknown Flag: "+data.getKey());
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 list; return CustomRegionManager.this.getWorldGuard();
} }
}
public WorldGuardPlugin getWorldGuard() {
return CustomRegionManager.this.getWorldGuard(); private WorldGuardPlugin getWorldGuard() {
} return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME));
} }
private WorldGuardPlugin getWorldGuard() { public RegionManager getWGManager(World world) {
return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME)); RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
} return container.get(BukkitAdapter.adapt(world));
}
public RegionManager getWGManager(World world) {
return getWorldGuard().getRegionManager(world); public String getRegionsHash(Location loc) {
} StringBuilder hash = new StringBuilder(loc.getWorld().getName());
List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitAdapter.asBlockVector(loc));
public String getRegionsHash(Location loc) { if (idlist.size() > 0) {
StringBuilder hash = new StringBuilder(loc.getWorld().getName()); hash.append("#");
List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(loc)); String[] ids = idlist.toArray(new String[idlist.size()]);
if (idlist.size() > 0) { if (ids.length > 1) {
hash.append("#"); Arrays.sort(ids);
String[] ids = idlist.toArray(new String[idlist.size()]); }
if (ids.length > 1) { hash.append(StringUtil.join(ids, ","));
Arrays.sort(ids); }
} return hash.toString();
hash.append(StringUtil.join(ids, ",")); }
}
return hash.toString(); public ApplicableRegions getRegionSet(Location loc) {
} return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(BukkitAdapter.asBlockVector(loc)), this.world(loc.getWorld()));
}
public ApplicableRegions getRegionSet(Location loc) {
return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(loc), this.world(loc.getWorld())); public ApplicableRegions getRegionSet(Block block) {
} return getRegionSet(block.getLocation());
}
public ApplicableRegions getRegionSet(Block block) {
return getRegionSet(block.getLocation()); public boolean isDiffrentRegion(Player player, Location loc) {
} return !getRegionsHash(loc).equals(mod.getPlayerData(player).getHash());
}
public boolean isDiffrentRegion(Player player, Location loc) { }
return !getRegionsHash(loc).equals(mod.getPlayerData(player).getHash());
}
}

View file

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