Compare commits

..

No commits in common. "master" and "spigot-1.9" have entirely different histories.

21 changed files with 1367 additions and 1636 deletions

View file

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

View file

@ -1,135 +1,140 @@
package de.jaschastarke.minecraft.limitedcreative; package de.jaschastarke.minecraft.limitedcreative;
import de.jaschastarke.bukkit.lib.CoreModule; import java.io.File;
import de.jaschastarke.minecraft.limitedcreative.inventories.*; import java.util.Map;
import de.jaschastarke.minecraft.limitedcreative.inventories.store.PlayerInventoryStorage; import java.util.WeakHashMap;
import de.jaschastarke.minecraft.limitedcreative.inventories.store.ReflectionStorage;
import de.jaschastarke.modularize.IModule; import org.bukkit.GameMode;
import de.jaschastarke.modularize.ModuleEntry; import org.bukkit.entity.Player;
import org.bukkit.GameMode; import org.bukkit.inventory.ItemStack;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import de.jaschastarke.bukkit.lib.CoreModule;
import de.jaschastarke.minecraft.limitedcreative.inventories.ArmoryConfig;
import java.io.File; import de.jaschastarke.minecraft.limitedcreative.inventories.Inventory;
import java.util.Map; import de.jaschastarke.minecraft.limitedcreative.inventories.InventoryConfig;
import java.util.WeakHashMap; import de.jaschastarke.minecraft.limitedcreative.inventories.InventoryPermissions;
import de.jaschastarke.minecraft.limitedcreative.inventories.PlayerListener;
public class ModInventories extends CoreModule<LimitedCreative> { import de.jaschastarke.minecraft.limitedcreative.inventories.store.InvYamlStorage;
protected PlayerInventoryStorage storage; import de.jaschastarke.minecraft.limitedcreative.inventories.store.PlayerInventoryStorage;
protected Map<Player, Inventory> inventories; import de.jaschastarke.modularize.IModule;
protected InventoryConfig config; import de.jaschastarke.modularize.ModuleEntry;
protected ArmoryConfig armor_config;
public class ModInventories extends CoreModule<LimitedCreative> {
public ModInventories(LimitedCreative plugin) { protected PlayerInventoryStorage storage;
super(plugin); protected Map<Player, Inventory> inventories;
} protected InventoryConfig config;
@Override protected ArmoryConfig armor_config;
public String getName() {
return "Inventory"; public ModInventories(LimitedCreative plugin) {
} super(plugin);
}
@Override @Override
public void initialize(ModuleEntry<IModule> entry) { public String getName() {
super.initialize(entry); return "Inventory";
listeners.addListener(new PlayerListener(this)); }
config = plugin.getPluginConfig().registerSection(new InventoryConfig(this, entry));
armor_config = config.registerSection(new ArmoryConfig(this)); @SuppressWarnings("deprecation")
@Override
if (Hooks.isAuthMePresent()) { public void initialize(ModuleEntry<IModule> entry) {
addModule(new de.jaschastarke.minecraft.limitedcreative.inventories.AuthMeInventories(plugin, this)); super.initialize(entry);
} listeners.addListener(new PlayerListener(this));
String incomp = Hooks.InventoryIncompatible.test(); config = plugin.getPluginConfig().registerSection(new InventoryConfig(this, entry));
if (config.getEnabled() && incomp != null) { armor_config = config.registerSection(new ArmoryConfig(this));
getLog().warn(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName()));
entry.deactivateUsage(); if (Hooks.isAuthMePresent()) {
} addModule(new de.jaschastarke.minecraft.limitedcreative.inventories.AuthMeInventories(plugin, this));
} }
@Override String incomp = Hooks.InventoryIncompatible.test();
public void onEnable() { if (config.getEnabled() && incomp != null) {
String incomp = Hooks.InventoryIncompatible.test(); getLog().warn(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName()));
if (incomp != null) { entry.deactivateUsage();
throw new IllegalAccessError(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName())); }
} }
super.onEnable(); @Override
//storage = new InvYamlStorage(this, new File(plugin.getDataFolder(), config.getFolder())); public void onEnable() {
storage = new ReflectionStorage(this, new File(plugin.getDataFolder(), config.getFolder())); String incomp = Hooks.InventoryIncompatible.test();
inventories = new WeakHashMap<Player, Inventory>(); if (incomp != null) {
getLog().info(plugin.getLocale().trans("basic.loaded.module")); throw new IllegalAccessError(plugin.getLocale().trans("inventory.warning.conflict", incomp, this.getName()));
} }
public InventoryConfig getConfig() { super.onEnable();
return config; storage = new InvYamlStorage(this, new File(plugin.getDataFolder(), config.getFolder()));
} inventories = new WeakHashMap<Player, Inventory>();
public ArmoryConfig getArmorConfig() { getLog().info(plugin.getLocale().trans("basic.loaded.module"));
return armor_config; }
} public InventoryConfig getConfig() {
return config;
public PlayerInventoryStorage getStorage() { }
return storage; public ArmoryConfig getArmorConfig() {
} return armor_config;
}
public Inventory getInventory(Player player) {
if (inventories.containsKey(player)) { public PlayerInventoryStorage getStorage() {
return inventories.get(player); return storage;
} else { }
Inventory inv = new Inventory(storage, player);
inventories.put(player, inv); public Inventory getInventory(Player player) {
return inv; if (inventories.containsKey(player)) {
} return inventories.get(player);
} } else {
Inventory inv = new Inventory(storage, player);
public void onSetGameMode(Player player, GameMode gm) { inventories.put(player, inv);
if (plugin.getPermManager().hasPermission(player, InventoryPermissions.KEEP_INVENTORY)) return inv;
return; }
player.closeInventory(); }
GameMode cgm = player.getGameMode(); public void onSetGameMode(Player player, GameMode gm) {
if (gm == GameMode.ADVENTURE && !config.getSeparateAdventure()) if (plugin.getPermManager().hasPermission(player, InventoryPermissions.KEEP_INVENTORY))
gm = GameMode.SURVIVAL; return;
else if (gm == GameMode.SPECTATOR) player.closeInventory();
gm = GameMode.CREATIVE;
if (cgm == GameMode.ADVENTURE && !config.getSeparateAdventure()) GameMode cgm = player.getGameMode();
cgm = GameMode.SURVIVAL; if (gm == GameMode.ADVENTURE && !config.getSeparateAdventure())
else if (cgm == GameMode.SPECTATOR) gm = GameMode.SURVIVAL;
cgm = GameMode.CREATIVE; else if (gm == GameMode.SPECTATOR)
gm = GameMode.CREATIVE;
if (gm != cgm) { if (cgm == GameMode.ADVENTURE && !config.getSeparateAdventure())
if (gm != GameMode.CREATIVE || config.getStoreCreative()) { cgm = GameMode.SURVIVAL;
getInventory(player).save(cgm); else if (cgm == GameMode.SPECTATOR)
} cgm = GameMode.CREATIVE;
if (gm == GameMode.CREATIVE) {
if (config.getStoreCreative() && getInventory(player).isStored(GameMode.CREATIVE)) { if (gm != cgm) {
getInventory(player).load(GameMode.CREATIVE); if (gm != GameMode.CREATIVE || config.getStoreCreative()) {
} else { getInventory(player).save(cgm);
getInventory(player).clear(); }
} if (gm == GameMode.CREATIVE) {
setCreativeArmor(player); if (config.getStoreCreative() && getInventory(player).isStored(GameMode.CREATIVE)) {
} else if (gm == GameMode.SURVIVAL) { getInventory(player).load(GameMode.CREATIVE);
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)) setCreativeArmor(player);
getInventory(player).load(GameMode.ADVENTURE); } 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) {
} if (getInventory(player).isStored(GameMode.ADVENTURE))
} getInventory(player).load(GameMode.ADVENTURE);
else
public void setCreativeArmor(Player player) { getInventory(player).clear();
if (!getPlugin().getPermManager().hasPermission(player, InventoryPermissions.BYPASS_CREATIVE_ARMOR)) { }
Map<String, ItemStack> armor = armor_config.getCreativeArmor(); }
if (armor != null) { }
ItemStack[] is = new ItemStack[4];
if (armor.containsKey("feet")) public void setCreativeArmor(Player player) {
is[0] = armor.get("feet"); if (!getPlugin().getPermManager().hasPermission(player, InventoryPermissions.BYPASS_CREATIVE_ARMOR)) {
if (armor.containsKey("legs")) Map<String, ItemStack> armor = armor_config.getCreativeArmor();
is[1] = armor.get("legs"); if (armor != null) {
if (armor.containsKey("chest")) ItemStack[] is = new ItemStack[4];
is[2] = armor.get("chest"); if (armor.containsKey("feet"))
if (armor.containsKey("head")) is[0] = armor.get("feet");
is[3] = armor.get("head"); if (armor.containsKey("legs"))
player.getInventory().setArmorContents(is); is[1] = armor.get("legs");
} 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,14 +82,8 @@ public class BlockState {
} }
//TODO Rename //TODO Rename
@SuppressWarnings("deprecation") public void setPlayerName(String s) {
public void setPlayerNameOrUUID(String s) { uuid = UUID.fromString(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() {
@ -121,7 +115,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)
setPlayerNameOrUUID(null); setPlayerName(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 com.sk89q.worldedit.WorldEdit; import java.util.Date;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitPlayer; import org.bukkit.Bukkit;
import com.sk89q.worldedit.math.BlockVector3; import org.bukkit.GameMode;
import com.sk89q.worldedit.regions.Region; import org.bukkit.Location;
import com.sk89q.worldedit.world.World; import org.bukkit.Material;
import de.jaschastarke.LocaleString; import org.bukkit.World;
import de.jaschastarke.bukkit.lib.chat.ChatFormattings; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import de.jaschastarke.bukkit.lib.commands.*; import com.sk89q.worldedit.bukkit.selections.Selection;
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.database.DBHelper; import de.jaschastarke.bukkit.lib.commands.BukkitCommand;
import de.jaschastarke.database.DatabaseConfigurationException; import de.jaschastarke.bukkit.lib.commands.CommandContext;
import de.jaschastarke.database.db.Database; 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.IHelpDescribed;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission; import de.jaschastarke.bukkit.lib.commands.MissingPermissionCommandException;
import de.jaschastarke.minecraft.limitedcreative.ModBlockStates; import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source; import de.jaschastarke.bukkit.lib.commands.annotations.Usages;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid; import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser;
import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.DBTransaction; import de.jaschastarke.bukkit.lib.database.DBHelper;
import de.jaschastarke.modularize.ModuleEntry.ModuleState; import de.jaschastarke.database.DatabaseConfigurationException;
import org.bukkit.Bukkit; import de.jaschastarke.database.db.Database;
import org.bukkit.GameMode; import de.jaschastarke.maven.ArchiveDocComments;
import org.bukkit.Location; import de.jaschastarke.maven.PluginCommand;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import java.util.Date; import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
import de.jaschastarke.minecraft.limitedcreative.blockstate.BlockState.Source;
/** import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.Cuboid;
* LimitedCreative-BlockState-Command: modify blockstate database to prevent drops of selected blocks (requires WorldEdit) import de.jaschastarke.minecraft.limitedcreative.blockstate.DBModel.DBTransaction;
* @usage /<command> - displays Regions-Command-Help import de.jaschastarke.modularize.ModuleEntry.ModuleState;
* @permission limitedcreative.blockstate.command
*/ /**
@ArchiveDocComments * LimitedCreative-BlockState-Command: modify blockstate database to prevent drops of selected blocks (requires WorldEdit)
@PluginCommand * @usage /<command> - displays Regions-Command-Help
public class BlockStateCommand extends BukkitCommand implements IHelpDescribed { * @permission limitedcreative.blockstate.command
private ModBlockStates mod; */
private HelpCommand help; @ArchiveDocComments
@PluginCommand
public BlockStateCommand() { public class BlockStateCommand extends BukkitCommand implements IHelpDescribed {
this.help = this.getDefaultHelpCommand(); private ModBlockStates mod;
} private HelpCommand help;
public BlockStateCommand(ModBlockStates mod) {
super(mod.getPlugin()); public BlockStateCommand() {
this.help = this.getDefaultHelpCommand(); this.help = this.getDefaultHelpCommand();
this.mod = mod; }
} public BlockStateCommand(ModBlockStates mod) {
super(mod.getPlugin());
@Override this.help = this.getDefaultHelpCommand();
public String getName() { this.mod = mod;
return "lcbs"; }
}
@Override
@Override public String getName() {
public String[] getAliases() { return "lcbs";
return new String[]{}; }
}
@Override
/** public String[] getAliases() {
* @internal has no effect, as not tested by any command handler return new String[]{};
* @see IHelpDescribed }
*/
@Override /**
public IAbstractPermission[] getRequiredPermissions() { * @internal has no effect, as not tested by any command handler
return new IAbstractPermission[]{BlockStatePermissions.COMMAND}; * @see IHelpDescribed
} */
@Override
@Override public IAbstractPermission[] getRequiredPermissions() {
public CharSequence[] getUsages() { return new IAbstractPermission[]{BlockStatePermissions.COMMAND};
return new String[]{"..."}; }
}
@Override
@Override public CharSequence[] getUsages() {
public CharSequence getDescription() { return new String[]{"..."};
return new LocaleString("command.blockstate"); }
}
@Override
@Override public CharSequence getDescription() {
public CharSequence getPackageName() { return new LocaleString("command.blockstate");
return mod.getPlugin().getName() + " - " + mod.getName(); }
}
@Override
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException { public CharSequence getPackageName() {
if (mod.getModuleEntry().getState() != ModuleState.ENABLED) return mod.getPlugin().getName() + " - " + mod.getName();
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");
* Deletes no longer used data from the BlockState-Database. Currently it only removes non-creative entries return super.execute(context, args);
* from the database, if you changed to "logSurvival"-config from true to false. }
*/
@IsCommand("cleanup") /**
@Usages("") * Deletes no longer used data from the BlockState-Database. Currently it only removes non-creative entries
public boolean cleanupDatabase(final CommandContext context, String... args) throws CommandException { * from the database, if you changed to "logSurvival"-config from true to false.
if (mod.getConfig().getLogSurvival()) { */
context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.nothing_to_cleanup")); @IsCommand("cleanup")
} else { @Usages("")
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new Runnable() { public boolean cleanupDatabase(final CommandContext context, String... args) throws CommandException {
@Override if (mod.getConfig().getLogSurvival()) {
public void run() { context.responseFormatted(ChatFormattings.INFO, L("command.blockstate.nothing_to_cleanup"));
int countDeleted = mod.getModel().cleanUp(DBModel.Cleanup.SURVIVAL); } else {
if (countDeleted < 0) mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new Runnable() {
context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.cleanup_error")); @Override
else public void run() {
context.responseFormatted(ChatFormattings.SUCCESS, L("command.blockstate.cleanup_success", countDeleted)); int countDeleted = mod.getModel().cleanUp(DBModel.Cleanup.SURVIVAL);
} if (countDeleted < 0)
}); context.responseFormatted(ChatFormattings.ERROR, L("command.blockstate.cleanup_error"));
} else
return true; context.responseFormatted(ChatFormattings.SUCCESS, L("command.blockstate.cleanup_success", countDeleted));
} }
});
/** }
* Modifies the BlockState-Database and sets all blocks in the selection to the provided gamemode. Set it return true;
* 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 /**
* @throws MissingPermissionCommandException * 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.
@IsCommand("set") * WorldEdit is required, because the selection Region is used.
@Usages("<gamemode>") * gamemode can be: survival / creative / adventure / s / c / a / 0 / 1 / 2
public boolean setGameMode(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException { * @throws MissingPermissionCommandException
if (!mod.getPlugin().getServer().getPluginManager().isPluginEnabled("WorldEdit")) { */
help.execute(context, new String[]{"set"}); @IsCommand("set")
context.response(L("command.blockstate.requires_worldedit")); @Usages("<gamemode>")
return true; public boolean setGameMode(final CommandContext context, String... args) throws CommandException, MissingPermissionCommandException {
} if (!mod.getPlugin().getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
if (!context.isPlayer()) { help.execute(context, new String[]{"set"});
context.response(L("cmdblock.blocked.not_console")); context.response(L("command.blockstate.requires_worldedit"));
return true; return true;
} }
if (args.length < 1) {// doesn't count parameters if (!context.isPlayer()) {
return false; context.response(L("cmdblock.blocked.not_console"));
} return true;
if (mod.getConfig().getIgnoredWorlds().contains(context.getPlayer().getWorld().getName())) { }
context.response(L("command.blockstate.world_ignored", context.getPlayer().getWorld().getName())); if (args.length < 1) {// doesn't count parameters
return true; return false;
} }
String gm = args[0].toLowerCase(); if (mod.getConfig().getIgnoredWorlds().contains(context.getPlayer().getWorld().getName())) {
final GameMode tgm; context.response(L("command.blockstate.world_ignored", context.getPlayer().getWorld().getName()));
if (gm.equals("0") || gm.equals("s") || gm.equals("survival")) return true;
tgm = GameMode.SURVIVAL; }
else if (gm.equals("1") || gm.equals("c") || gm.equals("creative")) String gm = args[0].toLowerCase();
tgm = GameMode.CREATIVE; final GameMode tgm;
else if (gm.equals("2") || gm.equals("a") || gm.equals("adventure")) if (gm.equals("0") || gm.equals("s") || gm.equals("survival"))
tgm = GameMode.ADVENTURE; tgm = GameMode.SURVIVAL;
else { else if (gm.equals("1") || gm.equals("c") || gm.equals("creative"))
return false; tgm = GameMode.CREATIVE;
} else if (gm.equals("2") || gm.equals("a") || gm.equals("adventure"))
tgm = GameMode.ADVENTURE;
BukkitPlayer bp = BukkitAdapter.adapt(context.getPlayer()); else {
Region region = null; return false;
try { }
region = WorldEdit.getInstance().getSessionManager().get(bp).getSelection(bp.getWorld());
} catch (Exception ignored) { //IncompleteRegionException WorldEditPlugin we = (WorldEditPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin("WorldEdit");
} final Selection selection = we.getSelection(context.getPlayer());
final Region selection = region; if (selection == null) {
if (selection == null) { context.response(L("command.blockstate.worledit_selection_empty"));
context.response(L("command.blockstate.worledit_selection_empty")); return true;
return true; }
}
final Location min = selection.getMinimumPoint();
final BlockVector3 min = selection.getMinimumPoint(); final Location max = selection.getMaximumPoint();
final BlockVector3 max = selection.getMaximumPoint();
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), new Runnable() {
mod.getPlugin().getServer().getScheduler().runTaskAsynchronously(mod.getPlugin(), () -> { @Override
if (mod.isDebug()) public void run() {
mod.getLog().debug("Scheduler: Asynchronous Task run"); if (mod.isDebug())
DBTransaction update = mod.getModel().groupUpdate(); mod.getLog().debug("Scheduler: Asynchronous Task run");
int count = 0; DBTransaction update = mod.getModel().groupUpdate();
World w = selection.getWorld(); int count = 0;
assert w != null; World w = selection.getWorld();
org.bukkit.World bw = BukkitAdapter.adapt(w);
Cuboid c = new Cuboid();
Cuboid c = new Cuboid(); c.add(min);
c.add(new Location(bw, min.getBlockX(), min.getBlockY(), min.getBlockZ())); c.add(max);
c.add(new Location(bw, max.getBlockX(), max.getBlockY(), max.getBlockZ())); mod.getModel().cacheStates(c);
mod.getModel().cacheStates(c);
BlockState seed = new BlockState();
BlockState seed = new BlockState(); seed.setPlayer(context.getPlayer());
seed.setPlayer(context.getPlayer()); seed.setGameMode(tgm);
seed.setGameMode(tgm); seed.setSource(Source.COMMAND);
seed.setSource(Source.COMMAND); seed.setDate(new Date());
seed.setDate(new Date()); for (int x = min.getBlockX(); x <= max.getBlockX(); x++) {
for (int x = min.getBlockX(); x <= max.getBlockX(); x++) { for (int y = min.getBlockY(); y <= max.getBlockY(); y++) {
for (int y = min.getBlockY(); y <= max.getBlockY(); y++) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) {
for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { Location loc = new Location(w, x, y, z);
BlockVector3 loc = BlockVector3.at(x, y, z); if (w.getBlockAt(loc).getType() != Material.AIR && selection.contains(loc)) {
if (!w.getBlock(loc).getBlockType().getMaterial().isAir() && selection.contains(loc)) { seed.setLocation(loc);
seed.setLocation(new Location(bw, x, y, z)); update.setState(new BlockState(seed));
update.setState(new BlockState(seed)); count++;
count++; }
} }
} }
} }
} update.finish();
update.finish();
context.response(L("command.blockstate.command_updated", count));
context.response(L("command.blockstate.command_updated", count)); }
}); });
return true; return true;
} }
/** /**
* Imports BlockState Data from a given Database to the current active Database. * 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.setPlayerNameOrUUID(rs.getString("player")); bs.setPlayerName(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.setPlayerNameOrUUID(rs.getString("player")); bs.setPlayerName(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.setPlayerNameOrUUID(rs.getString("player")); bs.setPlayerName(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.setPlayerNameOrUUID(rs.getString("player")); bs.setPlayerName(rs.getString("player"));
bs.setSource(getSource(rs)); bs.setSource(getSource(rs));
return bs; return bs;
} }

View file

@ -1,21 +1,22 @@
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
@ -23,11 +24,10 @@ 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 final Stack<Action> updateQueue = new Stack<Action>(); private Stack<Action> updateQueue = new Stack<Action>();
private boolean shutdown; private boolean shutdown = false;
private ModuleLogger log; private ModuleLogger log;
private ThreadedModel model; private ThreadedModel model;
private Thread thread; private Thread thread;
@ -39,8 +39,15 @@ 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.
*/ */
createThread(queries); thread = new DBThread(queries);
shutdown = true; //Don't allow the thread to run until it's started 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());
}
});
} }
private class DBThread extends Thread { private class DBThread extends Thread {
@ -55,8 +62,6 @@ 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)
@ -86,7 +91,6 @@ 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();
@ -100,7 +104,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 harmfully interupted"); log.severe("DB-Thread '" + Thread.currentThread().getName() + "' was harmfull interupted");
} }
Thread.yield(); Thread.yield();
} }
@ -108,49 +112,44 @@ 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.notifyAll(); updateQueue.notify();
} }
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 too long: " + (l2 - l) + "ms"); getLog().warn("queueUpdate-action took to long: " + (l - 2) + "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.notifyAll(); updateQueue.notify();
} }
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.notifyAll(); updateQueue.notify();
} }
} }
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.notifyAll(); updateQueue.notify();
} }
return act.getValue(); return act.getValue();
} }
@ -159,43 +158,38 @@ public class ThreadLink {
FetchCuboidAction action = new FetchCuboidAction(c); FetchCuboidAction action = new FetchCuboidAction(c);
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.push(action); updateQueue.push(action);
updateQueue.notifyAll(); updateQueue.notify();
} }
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.notifyAll(); updateQueue.notify();
} }
} }
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.notifyAll(); updateQueue.notify();
} }
} }
public void queueTransaction(Transaction transaction) { public void queueTransaction(Transaction transaction) {
restartThreadIfNeeded();
synchronized (updateQueue) { synchronized (updateQueue) {
updateQueue.add(transaction); updateQueue.add(transaction);
updateQueue.notifyAll(); updateQueue.notify();
} }
} }
public void shutdown() throws InterruptedException { public void shutdown() throws InterruptedException {
synchronized (updateQueue) { synchronized (updateQueue) {
shutdown = true; shutdown = true;
updateQueue.notifyAll(); updateQueue.notify();
} }
thread.join(THREAD_SHUTDOWN_WAIT_MS); thread.join();
if (thread.isAlive())
thread.interrupt(); //Wake it up
} }
public HasBlockState getMetaState(Block block) { public HasBlockState getMetaState(Block block) {
@ -215,27 +209,4 @@ 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,24 +1,25 @@
package de.jaschastarke.minecraft.limitedcreative.blockstate.worldedit; package de.jaschastarke.minecraft.limitedcreative.blockstate.worldedit;
import com.sk89q.worldedit.WorldEditException; import java.util.Date;
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 java.util.Date; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent;
public class EditSessionExtent extends AbstractDelegateExtent { import de.jaschastarke.minecraft.limitedcreative.ModBlockStates;
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;
@ -29,15 +30,14 @@ public class EditSessionExtent extends AbstractDelegateExtent {
/** /**
* Called when a block is being changed. * Called when a block is being changed.
* *
* @param pt the position * @param position the position
* @param newBlock the new block to replace the old one * @param newBlock the new block to replace the old one
*/ */
@Override protected void onBlockChange(Vector pt, BaseBlock newBlock) {
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.getBlockType().getMaterial().isAir()) { if (newBlock.getType() == 0) {
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,15 +46,13 @@ public class EditSessionExtent extends AbstractDelegateExtent {
s.setLocation(loc); s.setLocation(loc);
} }
s.setGameMode(null); s.setGameMode(null);
s.setPlayerNameOrUUID(player.getUniqueId().toString()); s.setPlayerName(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,17 +1,18 @@
package de.jaschastarke.minecraft.limitedcreative.hooks; package de.jaschastarke.minecraft.limitedcreative.hooks;
import de.jaschastarke.minecraft.limitedcreative.Hooks;
import de.jaschastarke.minecraft.limitedcreative.LimitedCreative;
import fr.xephi.authme.api.v3.AuthMeApi;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
//@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime import uk.org.whoami.authme.api.API;
import de.jaschastarke.minecraft.limitedcreative.Hooks;
import de.jaschastarke.minecraft.limitedcreative.LimitedCreative;
@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 = AuthMeApi.getInstance().isAuthenticated(player); boolean li = API.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,15 +1,16 @@
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;
//@Deprecated // AuthMe 3.0 released. Compatibility for older versions will be removed sometime import uk.org.whoami.authme.events.RestoreInventoryEvent;
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) {
@ -18,16 +19,16 @@ public class AuthMeInventories extends SimpleModule<LimitedCreative> implements
} }
@EventHandler @EventHandler
public void onStoreInventory(ProtectInventoryEvent event) { public void onStoreInventory(StoreInventoryEvent 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, false))); load(pinv, YamlConfiguration.loadConfiguration(getFile(pinv, target)));
} }
@Override @Override
@ -52,11 +52,7 @@ 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 {
File nameFile=getFile(pinv, target, false); yml.save(getFile(pinv, target));
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();
@ -65,28 +61,19 @@ public class InvYamlStorage extends InvConfStorage {
@Override @Override
public void remove(Inventory pinv, Target target) { public void remove(Inventory pinv, Target target) {
getFile(pinv, target, true).delete(); getFile(pinv, target).delete();
} }
@Override @Override
public boolean contains(Inventory pinv, Target target) { public boolean contains(Inventory pinv, Target target) {
return getFile(pinv, target, false).exists(); return getFile(pinv, target).exists();
} }
protected File getFile(Inventory pinv, Target target, boolean uuidonly) { protected File getFile(Inventory pinv, Target target) {
File file; if (target != default_target) {
String player; return new File(dir, pinv.getPlayer().getUniqueId() + "_" + target.toString().toLowerCase() + SUFFIX);
do { } else {
player = uuidonly ? pinv.getPlayer().getUniqueId().toString() : pinv.getPlayer().getName(); return new File(dir, pinv.getPlayer().getUniqueId() + SUFFIX);
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

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

View file

@ -1,280 +1,282 @@
package de.jaschastarke.minecraft.limitedcreative.regions; package de.jaschastarke.minecraft.limitedcreative.regions;
import com.sk89q.worldedit.bukkit.BukkitAdapter; import java.util.ArrayList;
import com.sk89q.worldguard.WorldGuard; import java.util.List;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet; import org.apache.commons.lang.StringUtils;
import com.sk89q.worldguard.protection.flags.Flag; import org.bukkit.Bukkit;
import com.sk89q.worldguard.protection.flags.FlagContext; import org.bukkit.ChatColor;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat; import org.bukkit.World;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.RegionContainer; import com.sk89q.worldguard.protection.flags.Flag;
import de.jaschastarke.LocaleString; import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import de.jaschastarke.bukkit.lib.chat.ChatFormattings; import com.sk89q.worldguard.protection.managers.RegionManager;
import de.jaschastarke.bukkit.lib.commands.*; import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand; import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import de.jaschastarke.bukkit.lib.commands.annotations.Usages;
import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser; import de.jaschastarke.LocaleString;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion; import de.jaschastarke.bukkit.lib.chat.ChatFormattings;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Completer; import de.jaschastarke.bukkit.lib.commands.BukkitCommand;
import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Context; import de.jaschastarke.bukkit.lib.commands.CommandContext;
import de.jaschastarke.maven.ArchiveDocComments; import de.jaschastarke.bukkit.lib.commands.CommandException;
import de.jaschastarke.maven.PluginCommand; import de.jaschastarke.bukkit.lib.commands.HelpCommand;
import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission; import de.jaschastarke.bukkit.lib.commands.ICommand;
import de.jaschastarke.minecraft.limitedcreative.ModRegions; import de.jaschastarke.bukkit.lib.commands.IHelpDescribed;
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagList; import de.jaschastarke.bukkit.lib.commands.MethodCommand;
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagValue; import de.jaschastarke.bukkit.lib.commands.MissingPermissionCommandException;
import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.Region; import de.jaschastarke.bukkit.lib.commands.annotations.IsCommand;
import de.jaschastarke.modularize.ModuleEntry.ModuleState; import de.jaschastarke.bukkit.lib.commands.annotations.Usages;
import org.apache.commons.lang.StringUtils; import de.jaschastarke.bukkit.lib.commands.parser.DefinedParameterParser;
import org.bukkit.Bukkit; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion;
import org.bukkit.ChatColor; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Completer;
import org.bukkit.World; import de.jaschastarke.bukkit.lib.commands.parser.TabCompletion.Context;
import de.jaschastarke.maven.ArchiveDocComments;
import java.util.ArrayList; import de.jaschastarke.maven.PluginCommand;
import java.util.List; import de.jaschastarke.minecraft.lib.permissions.IAbstractPermission;
import de.jaschastarke.minecraft.limitedcreative.ModRegions;
/** import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagList;
* LimitedCreative-Region-Command: configure creative regions import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.FlagValue;
* @usage /<command> - displays Regions-Command-Help import de.jaschastarke.minecraft.limitedcreative.regions.worldguard.Region;
* @permission limitedcreative.region import de.jaschastarke.modularize.ModuleEntry.ModuleState;
*/
@ArchiveDocComments /**
@PluginCommand * LimitedCreative-Region-Command: configure creative regions
public class RegionsCommand extends BukkitCommand implements IHelpDescribed { * @usage /<command> - displays Regions-Command-Help
private final static String GLOBAL_REGION = "__global__"; * @permission limitedcreative.region
private ModRegions mod; */
private HelpCommand help; @ArchiveDocComments
private WorldGuardPlugin wg; @PluginCommand
public class RegionsCommand extends BukkitCommand implements IHelpDescribed {
public RegionsCommand() { private final static String GLOBAL_REGION = "__global__";
this.help = this.getDefaultHelpCommand(); private ModRegions mod;
} private HelpCommand help;
public RegionsCommand(ModRegions mod) { private WorldGuardPlugin wg;
super(mod.getPlugin());
this.help = this.getDefaultHelpCommand(); public RegionsCommand() {
this.mod = mod; this.help = this.getDefaultHelpCommand();
this.wg = (WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME); }
fullfillTabCompletion(); public RegionsCommand(ModRegions mod) {
} super(mod.getPlugin());
this.help = this.getDefaultHelpCommand();
@Override this.mod = mod;
public String getName() { this.wg = (WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME);
return "lcr"; fullfillTabCompletion();
} }
@Override @Override
public String[] getAliases() { public String getName() {
return new String[]{"/region"}; return "lcr";
} }
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException { @Override
if (mod.getModuleEntry().getState() != ModuleState.ENABLED) public String[] getAliases() {
throw new CommandException("Module " + mod.getName() + " is disabled"); return new String[]{"/region"};
return super.execute(context, args); }
}
public boolean execute(final CommandContext context, final String[] args) throws MissingPermissionCommandException, CommandException {
/** if (mod.getModuleEntry().getState() != ModuleState.ENABLED)
* @internal has no effect, as not tested by any command handler throw new CommandException("Module " + mod.getName() + " is disabled");
* @see IHelpDescribed return super.execute(context, args);
*/ }
@Override
public IAbstractPermission[] getRequiredPermissions() { /**
return new IAbstractPermission[]{RegionPermissions.REGION}; * @internal has no effect, as not tested by any command handler
} * @see IHelpDescribed
@Override */
public String[] getUsages() { @Override
return null; public IAbstractPermission[] getRequiredPermissions() {
} return new IAbstractPermission[]{RegionPermissions.REGION};
@Override }
public CharSequence getDescription() { @Override
return new LocaleString("command.regions"); public String[] getUsages() {
} return null;
@Override }
public String getPackageName() { @Override
return mod.getPlugin().getName() + " - " + mod.getName(); public CharSequence getDescription() {
} return new LocaleString("command.regions");
}
/*@Override @Override
public IPermission getPermission(String subPerm) { public String getPackageName() {
if (subPerm.equals("region")) return mod.getPlugin().getName() + " - " + mod.getName();
return RegionPermissions.REGION; }
else
return RegionPermissions.REGION.getPermission(subPerm); /*@Override
}*/ public IPermission getPermission(String subPerm) {
if (subPerm.equals("region"))
protected void fullfillTabCompletion() { return RegionPermissions.REGION;
for (ICommand cmd : handler.getCommands()) { else
if (cmd instanceof MethodCommand) { return RegionPermissions.REGION.getPermission(subPerm);
if (cmd.getName().equals("info")) { }*/
((MethodCommand) cmd).getCompleter().add(TabCompletion.forUsageLine("[region]"));
} protected void fullfillTabCompletion() {
for (TabCompletion c : ((MethodCommand) cmd).getCompleter()) { for (ICommand cmd : handler.getCommands()) {
c.setCompleter("region", new RegionCompleter()); if (cmd instanceof MethodCommand) {
} 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();
for (int i = 0; i < args.length; i++) { private class RegionCompleter implements Completer {
if (args[i].equals("world")) { @Override
idx = i; public List<String> get(Context context, String arg) {
break; int idx = -1;
} String[] args = context.getHelper().getArguments();
} for (int i = 0; i < args.length; i++) {
World w = context.getCommandContext().isPlayer() ? context.getCommandContext().getPlayer().getWorld() : null; if (args[i].equals("world")) {
if (idx > -1 && context.getArgument(idx) != null) idx = i;
w = Bukkit.getWorld(context.getArgument(idx)); break;
if (w != null) { }
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); }
RegionManager mgr = container.get(BukkitAdapter.adapt(w)); World w = context.getCommandContext().isPlayer() ? context.getCommandContext().getPlayer().getWorld() : null;
if (mgr != null) { if (idx > -1 && context.getArgument(idx) != null)
List<String> hints = new ArrayList<String>(); w = Bukkit.getWorld(context.getArgument(idx));
for (String rId : mgr.getRegions().keySet()) { if (w != null) {
if (rId.toLowerCase().startsWith(arg.toLowerCase())) RegionManager mgr = getWorldGuard().getRegionManager(w);
hints.add(rId); if (mgr != null) {
} List<String> hints = new ArrayList<String>();
return hints; for (String rId : mgr.getRegions().keySet()) {
} 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)
*/ /**
@IsCommand("flag") * Sets the Flag of a region to a new value. If no value given, the flag is removed.
//@NeedsPermission("region") // not needed as the whole command requires permissions * -g sets the affected group of the flag, instead the flag (equivalent to using flag-group as flag-name)
@Usages("<region> -g <flag> -w world [value]") * -w world uses a world by name instead the world your in (required from console)
public boolean setFlag(CommandContext context, String... args) throws CommandException, MissingPermissionCommandException { */
DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"g"}, 2); @IsCommand("flag")
if (params.getArgumentCount() < 2) {// doesn't count parameters //@NeedsPermission("region") // not needed as the whole command requires permissions
help.execute(context, new String[]{"flag"}); @Usages("<region> -g <flag> -w world [value]")
context.response(L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender())); public boolean setFlag(CommandContext context, String... args) throws CommandException, MissingPermissionCommandException {
return true; DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"g"}, 2);
} if (params.getArgumentCount() < 2) {// doesn't count parameters
help.execute(context, new String[]{"flag"});
World w = context.isPlayer() ? context.getPlayer().getWorld() : null; context.response(L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender()));
if (params.getParameter("-w") != null) return true;
w = mod.getPlugin().getServer().getWorld(params.getParameter("-w")); }
if (w == null)
throw new CommandException(L("command.worldguard.world_not_found")); World w = context.isPlayer() ? context.getPlayer().getWorld() : null;
if (params.getParameter("-w") != null)
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); w = mod.getPlugin().getServer().getWorld(params.getParameter("-w"));
RegionManager mgr = container.get(BukkitAdapter.adapt(w)); if (w == null)
ProtectedRegion region = mgr.getRegion(params.getArgument(0)); throw new CommandException(L("command.worldguard.world_not_found"));
if (region == null && params.getArgument(0).equalsIgnoreCase("__global__")) {
region = new GlobalProtectedRegion(params.getArgument(0)); RegionManager mgr = getWorldGuard().getRegionManager(w);
mgr.addRegion(region); ProtectedRegion region = mgr.getRegion(params.getArgument(0));
} if (region == null && params.getArgument(0).equalsIgnoreCase("__global__")) {
if (region == null) region = new GlobalProtectedRegion(params.getArgument(0));
throw new CommandException(L("command.worldguard.region_not_found")); mgr.addRegion(region);
}
Region reg = mod.getRegionManager().world(w).region(region); if (region == null)
throw new CommandException(L("command.worldguard.region_not_found"));
Flag<?> flag = FlagList.getFlag(params.getArgument(1));
if (flag == null) { Region reg = mod.getRegionManager().world(w).region(region);
String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "\n"
+ L("command.worldguard.available_flags") + FlagList.getStringListAvailableFlags(context.getSender()); Flag<?> flag = FlagList.getFlag(params.getArgument(1));
throw new CommandException(msg); if (flag == null) {
} else if (params.getFlags().contains("g")) { String msg = L("command.worldguard.unknown_flag") + params.getArgument(1) + "\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" } 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) {
} 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) {
reg.setFlag(flag, flag.parseInput(FlagContext.create().setInput(value).build())); String value = params.getValue();
} else { try {
reg.setFlag(flag, null); if (value != null && value.trim().length() > 0) {
} reg.setFlag(flag, flag.parseInput(getWorldGuard(), context.getSender(), value));
} catch (InvalidFlagFormat e) { } else {
context.response(context.getFormatter().formatString(ChatFormattings.ERROR, e.getLocalizedMessage())); reg.setFlag(flag, null);
return true; }
} } catch (InvalidFlagFormat e) {
context.response(context.getFormatter().formatString(ChatFormattings.ERROR, e.getLocalizedMessage()));
context.response(L("command.worldguard.flag_set", flag.getName())); return true;
return true; }
}
context.response(L("command.worldguard.flag_set", flag.getName()));
@IsCommand("info") return true;
//@NeedsPermission("region") }
@Usages("[world] [region]")
public boolean getInfo(CommandContext context, String... args) throws CommandException { @IsCommand("info")
DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"s"}, 1); //@NeedsPermission("region")
@Usages("[world] [region]")
if (context.isPlayer()) { public boolean getInfo(CommandContext context, String... args) throws CommandException {
/* DefinedParameterParser params = new DefinedParameterParser(args, new String[]{"s"}, 1);
* WorldEdits intercepting Servers privates commandMap via Reflections realy sucks!
* Just because they are to lazy to add all the lines commands to plugin.yml if (context.isPlayer()) {
*/ /*
String orgCmd = ("region info " + StringUtils.join(args)).trim(); * WorldEdits intercepting Servers privates commandMap via Reflections realy sucks!
mod.getPlugin().getServer().dispatchCommand(context.getSender(), orgCmd); * Just because they are to lazy to add all the lines commands to plugin.yml
} */
String orgCmd = ("region info " + StringUtils.join(args)).trim();
World w = context.isPlayer() ? context.getPlayer().getWorld() : null; mod.getPlugin().getServer().dispatchCommand(context.getSender(), orgCmd);
if (params.getArgumentCount() > 1) }
w = mod.getPlugin().getServer().getWorld(params.getArgument(0));
if (w == null) World w = context.isPlayer() ? context.getPlayer().getWorld() : null;
throw new CommandException(L("command.worldguard.world_not_found")); if (params.getArgumentCount() > 1)
w = mod.getPlugin().getServer().getWorld(params.getArgument(0));
ProtectedRegion region = null; if (w == null)
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); throw new CommandException(L("command.worldguard.world_not_found"));
if (params.getArgumentCount() == 0 && context.isPlayer()) {
RegionManager mgr = container.get(BukkitAdapter.adapt(context.getPlayer().getWorld())); ProtectedRegion region = null;
ApplicableRegionSet set = mgr.getApplicableRegions(BukkitAdapter.asBlockVector(context.getPlayer().getLocation())); if (params.getArgumentCount() == 0 && context.isPlayer()) {
if (set.size() > 0) { RegionManager mgr = getWorldGuard().getRegionManager(context.getPlayer().getWorld());
region = set.iterator().next(); ApplicableRegionSet set = mgr.getApplicableRegions(context.getPlayer().getLocation());
} else { if (set.size() > 0) {
region = container.get(BukkitAdapter.adapt(w)).getRegion(GLOBAL_REGION); region = set.iterator().next();
} } else {
} else { region = getWorldGuard().getRegionManager(w).getRegion(GLOBAL_REGION);
int rpc = params.getArgumentCount() > 1 ? 1 : 0; }
RegionManager mgr = container.get(BukkitAdapter.adapt(w)); } else {
region = mgr.getRegion(params.getArgument(rpc)); int rpc = params.getArgumentCount() > 1 ? 1 : 0;
if (region == null && params.getArgument(rpc).equalsIgnoreCase(GLOBAL_REGION)) { RegionManager mgr = getWorldGuard().getRegionManager(w);
region = new GlobalProtectedRegion(params.getArgument(rpc)); region = mgr.getRegion(params.getArgument(rpc));
mgr.addRegion(region); if (region == null && params.getArgument(rpc).equalsIgnoreCase(GLOBAL_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)
Region reg = mod.getRegionManager().world(w).region(region); throw new CommandException(L("command.worldguard.region_not_found"));
StringBuilder list = new StringBuilder(); Region reg = mod.getRegionManager().world(w).region(region);
for (FlagValue data : reg.getFlags()) {
if (list.length() > 0) StringBuilder list = new StringBuilder();
list.append(", "); for (FlagValue data : reg.getFlags()) {
list.append(data.getFlag().getName()); if (list.length() > 0)
list.append(": "); list.append(", ");
list.append(data.getValue().toString()); list.append(data.getFlag().getName());
} 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,189 +1,192 @@
/* /*
* 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 com.sk89q.worldedit.bukkit.BukkitAdapter; import java.io.File;
import com.sk89q.worldguard.WorldGuard; import java.io.IOException;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import java.util.ArrayList;
import com.sk89q.worldguard.protection.flags.Flag; import java.util.Arrays;
import com.sk89q.worldguard.protection.managers.RegionManager; import java.util.HashMap;
import com.sk89q.worldguard.protection.regions.ProtectedRegion; import java.util.List;
import com.sk89q.worldguard.protection.regions.RegionContainer; import java.util.Map;
import de.jaschastarke.minecraft.limitedcreative.ModRegions;
import de.jaschastarke.minecraft.limitedcreative.regions.WorldGuardIntegration; import org.bukkit.Location;
import de.jaschastarke.utils.StringUtil; import org.bukkit.World;
import org.bukkit.Location; import org.bukkit.block.Block;
import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.block.Block; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import com.sk89q.worldguard.bukkit.BukkitUtil;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import java.io.File; import com.sk89q.worldguard.protection.flags.Flag;
import java.io.IOException; import com.sk89q.worldguard.protection.managers.RegionManager;
import java.util.*; import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class CustomRegionManager { import de.jaschastarke.minecraft.limitedcreative.ModRegions;
protected YamlConfiguration c; import de.jaschastarke.minecraft.limitedcreative.regions.WorldGuardIntegration;
protected File file; import de.jaschastarke.utils.StringUtil;
private Map<World, CWorld> worlds = new HashMap<World, CWorld>();
private ModRegions mod; public class CustomRegionManager {
public CustomRegionManager(File file, ModRegions mod) { protected YamlConfiguration c;
this.file = file; protected File file;
this.mod = mod; private Map<World, CWorld> worlds = new HashMap<World, CWorld>();
c = YamlConfiguration.loadConfiguration(file); private ModRegions mod;
} public CustomRegionManager(File file, ModRegions mod) {
this.file = file;
this.mod = mod;
public CWorld world(World w) { c = YamlConfiguration.loadConfiguration(file);
if (worlds.containsKey(w)) { }
return worlds.get(w);
} else {
CWorld r = new CWorld(w); public CWorld world(World w) {
worlds.put(w, r); if (worlds.containsKey(w)) {
return r; return worlds.get(w);
} } else {
} CWorld r = new CWorld(w);
worlds.put(w, r);
public class CWorld { return r;
private World world; }
private ConfigurationSection wc = null; }
public CWorld(World w) {
world = w; public class CWorld {
} private World world;
public CustomRegionManager getManager() { private ConfigurationSection wc = null;
return CustomRegionManager.this; public CWorld(World w) {
} world = w;
private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>(); }
public Region region(ProtectedRegion pr) { public CustomRegionManager getManager() {
if (regions.containsKey(pr)) { return CustomRegionManager.this;
return regions.get(pr); }
} else { private Map<ProtectedRegion, Region> regions = new HashMap<ProtectedRegion, Region>();
Region r = new Region(this, pr); public Region region(ProtectedRegion pr) {
regions.put(pr, r); if (regions.containsKey(pr)) {
return r; return regions.get(pr);
} } else {
} Region r = new Region(this, pr);
public World getWorld() { regions.put(pr, r);
return world; return r;
} }
public ProtectedRegion getGlobalRegion() { }
return getWGManager(world).getRegion("__global__"); public World getWorld() {
} return world;
}
@SuppressWarnings("unchecked") public ProtectedRegion getGlobalRegion() {
public <V> void storeFlag(Region region, Flag<V> flag, Object value) { return getWGManager(world).getRegion("__global__");
if (wc == null) { }
if (c.contains(world.getName().toLowerCase()))
wc = c.getConfigurationSection(world.getName().toLowerCase()); @SuppressWarnings("unchecked")
else public <V> void storeFlag(Region region, Flag<V> flag, Object value) {
wc = c.createSection(world.getName().toLowerCase()); if (wc == null) {
} if (c.contains(world.getName().toLowerCase()))
wc = c.getConfigurationSection(world.getName().toLowerCase());
ConfigurationSection rs; else
if (wc.contains(region.getProtectedRegion().getId())) wc = c.createSection(world.getName().toLowerCase());
rs = wc.getConfigurationSection(region.getProtectedRegion().getId()); }
else
rs = wc.createSection(region.getProtectedRegion().getId()); ConfigurationSection rs;
if (wc.contains(region.getProtectedRegion().getId()))
ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags"); rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
else
if (value == null) { rs = wc.createSection(region.getProtectedRegion().getId());
fs.set(flag.getName(), null);
} else { ConfigurationSection fs = rs.contains("flags") ? rs.getConfigurationSection("flags") : rs.createSection("flags");
fs.set(flag.getName(), flag.marshal((V) value));
} if (value == null) {
fs.set(flag.getName(), null);
try { } else {
c.save(file); fs.set(flag.getName(), flag.marshal((V) value));
} catch (IOException e) { }
e.printStackTrace();
} try {
} c.save(file);
public List<FlagValue> getFlags(Region region) { } catch (IOException e) {
List<FlagValue> list = new ArrayList<FlagValue>(); e.printStackTrace();
}
if (c.contains(world.getName().toLowerCase())) { }
ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase()); public List<FlagValue> getFlags(Region region) {
if (wc.contains(region.getProtectedRegion().getId())) { List<FlagValue> list = new ArrayList<FlagValue>();
ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
if (rs.contains("flags")) { if (c.contains(world.getName().toLowerCase())) {
ConfigurationSection fs = rs.getConfigurationSection("flags"); ConfigurationSection wc = c.getConfigurationSection(world.getName().toLowerCase());
for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) { if (wc.contains(region.getProtectedRegion().getId())) {
Flag<?> flag = null; ConfigurationSection rs = wc.getConfigurationSection(region.getProtectedRegion().getId());
if (data.getKey().endsWith("-group")) { if (rs.contains("flags")) {
flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6)); ConfigurationSection fs = rs.getConfigurationSection("flags");
if (flag != null) for (Map.Entry<String, Object> data : fs.getValues(false).entrySet()) {
flag = flag.getRegionGroupFlag(); Flag<?> flag = null;
} else { if (data.getKey().endsWith("-group")) {
flag = FlagList.getFlag(data.getKey()); flag = FlagList.getFlag(data.getKey().substring(0, data.getKey().length() - 6));
} if (flag != null)
if (flag != null) { // the flag doesn't exists anymore. just ignore it without error flag = flag.getRegionGroupFlag();
Object value = flag.unmarshal(data.getValue()); } else {
list.add(new FlagValue(flag, value)); flag = FlagList.getFlag(data.getKey());
} else { }
if (mod.isDebug()) if (flag != null) { // the flag doesn't exists anymore. just ignore it without error
mod.getLog().debug("Couldn't load unknown Flag: "+data.getKey()); Object value = flag.unmarshal(data.getValue());
} list.add(new FlagValue(flag, value));
} } else {
} if (mod.isDebug())
} mod.getLog().debug("Couldn't load unknown Flag: "+data.getKey());
} }
return list; }
} }
}
public WorldGuardPlugin getWorldGuard() { }
return CustomRegionManager.this.getWorldGuard(); return list;
} }
}
public WorldGuardPlugin getWorldGuard() {
private WorldGuardPlugin getWorldGuard() { return CustomRegionManager.this.getWorldGuard();
return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME)); }
} }
public RegionManager getWGManager(World world) { private WorldGuardPlugin getWorldGuard() {
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); return ((WorldGuardPlugin) mod.getPlugin().getServer().getPluginManager().getPlugin(WorldGuardIntegration.PLUGIN_NAME));
return container.get(BukkitAdapter.adapt(world)); }
}
public RegionManager getWGManager(World world) {
public String getRegionsHash(Location loc) { return getWorldGuard().getRegionManager(world);
StringBuilder hash = new StringBuilder(loc.getWorld().getName()); }
List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitAdapter.asBlockVector(loc));
if (idlist.size() > 0) { public String getRegionsHash(Location loc) {
hash.append("#"); StringBuilder hash = new StringBuilder(loc.getWorld().getName());
String[] ids = idlist.toArray(new String[idlist.size()]); List<String> idlist = getWGManager(loc.getWorld()).getApplicableRegionsIDs(BukkitUtil.toVector(loc));
if (ids.length > 1) { if (idlist.size() > 0) {
Arrays.sort(ids); hash.append("#");
} String[] ids = idlist.toArray(new String[idlist.size()]);
hash.append(StringUtil.join(ids, ",")); if (ids.length > 1) {
} Arrays.sort(ids);
return hash.toString(); }
} hash.append(StringUtil.join(ids, ","));
}
public ApplicableRegions getRegionSet(Location loc) { return hash.toString();
return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(BukkitAdapter.asBlockVector(loc)), this.world(loc.getWorld())); }
}
public ApplicableRegions getRegionSet(Location loc) {
public ApplicableRegions getRegionSet(Block block) { return new ApplicableRegions(getWGManager(loc.getWorld()).getApplicableRegions(loc), this.world(loc.getWorld()));
return getRegionSet(block.getLocation()); }
}
public ApplicableRegions getRegionSet(Block block) {
public boolean isDiffrentRegion(Player player, Location loc) { return getRegionSet(block.getLocation());
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

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