Add checkstyle to enforce formatting, change all formatting to comply

This commit is contained in:
Thijs Wiefferink 2017-03-29 20:15:44 +02:00
parent f471b9bbf0
commit dad502ec0c
94 changed files with 3984 additions and 3454 deletions

5
.gitignore vendored
View File

@ -30,4 +30,7 @@ local.properties
# IntelliJ IDEA
*.iml
.idea
dependency-reduced-pom.xml
dependency-reduced-pom.xml
desktop.ini
.*

View File

@ -1,253 +1,258 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.4.0</version> <!-- Main plugin version -->
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>
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.4.0</version> <!-- Main plugin version -->
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<!-- Bukkit, AreaShop aims to support 1.7.9+, but this is the lowest Bukkit version available from the Spigot repo, Bukkit repository is gone -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependencies>
<!-- Bukkit, AreaShop aims to support 1.7.9+, but this is the lowest Bukkit version available from the Spigot repo, Bukkit repository is gone -->
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- InteractiveMessenger library -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>interactivemessenger</artifactId>
<version>1.0</version>
</dependency>
<!-- InteractiveMessenger library -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>interactivemessenger</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-5</artifactId>
<version>WorldGuard-5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-6</artifactId>
<version>WorldGuard-6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-6_1_3</artifactId>
<version>WorldGuard-6_1_3</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-5</artifactId>
<version>WorldEdit-5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-6</artifactId>
<version>WorldEdit-6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-5</artifactId>
<version>WorldGuard-5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-6</artifactId>
<version>WorldGuard-6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-6_1_3</artifactId>
<version>WorldGuard-6_1_3</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-5</artifactId>
<version>WorldEdit-5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-6</artifactId>
<version>WorldEdit-6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<profiles>
<!-- Copy the jar file to a test server, activate by using -DcopyResult="/path/to/test/server" -->
<profile>
<id>test-locally</id>
<activation>
<property>
<name>copyResult</name>
</property>
</activation>
<build>
<profiles>
<!-- Copy the jar file to a test server, activate by using -DcopyResult="/path/to/test/server" -->
<profile>
<id>test-locally</id>
<activation>
<property>
<name>copyResult</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<configuration>
<target>
<copy file="./target/${project.build.finalName}.jar"
tofile="${copyResult}\${project.build.finalName}.jar"/>
</target>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Package the source files in a jar, activate by using -Dsources -->
<profile>
<id>package-sources</id>
<activation>
<property>
<name>sources</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Produce javadoc files, activate by using -Djavadoc -->
<profile>
<id>generate-javadoc</id>
<activation>
<property>
<name>javadoc</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<excludePackageNames>me.wiefferink.areashop.lib</excludePackageNames>
<destDir>${javadoc}</destDir>
<links>
<link>https://hub.spigotmc.org/javadocs/bukkit/</link>
<link>http://docs.sk89q.com/worldedit/apidocs/</link>
<link>http://docs.sk89q.com/worldguard/apidocs/</link>
</links>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<finalName>AreaShop</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>hiddenConfig.yml</include>
<include>default.yml</include>
<include>README.md</include>
<include>lang/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<configuration>
<target>
<copy file="./target/${project.build.finalName}.jar" tofile="${copyResult}\${project.build.finalName}.jar"/>
</target>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<!-- Relocate messaging framework -->
<relocation>
<pattern>me.wiefferink.interactivemessenger</pattern>
<shadedPattern>me.wiefferink.areashop.interactivemessenger</shadedPattern>
</relocation>
<!-- Relocate bstats -->
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.wiefferink.areashop.bstats</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
<!-- Package the source files in a jar, activate by using -Dsources -->
<profile>
<id>package-sources</id>
<activation>
<property>
<name>sources</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Produce javadoc files, activate by using -Djavadoc -->
<profile>
<id>generate-javadoc</id>
<activation>
<property>
<name>javadoc</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<excludePackageNames>me.wiefferink.areashop.lib</excludePackageNames>
<destDir>${javadoc}</destDir>
<links>
<link>https://hub.spigotmc.org/javadocs/bukkit/</link>
<link>http://docs.sk89q.com/worldedit/apidocs/</link>
<link>http://docs.sk89q.com/worldguard/apidocs/</link>
</links>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<finalName>AreaShop</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>hiddenConfig.yml</include>
<include>default.yml</include>
<include>README.md</include>
<include>lang/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<!-- Relocate messaging framework -->
<relocation>
<pattern>me.wiefferink.interactivemessenger</pattern>
<shadedPattern>me.wiefferink.areashop.interactivemessenger</shadedPattern>
</relocation>
<!-- Relocate bstats -->
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.wiefferink.areashop.bstats</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
</plugin>
</plugins>
</build>
</build>
</project>

View File

@ -12,7 +12,11 @@ import me.wiefferink.areashop.listeners.PlayerLoginLogoutListener;
import me.wiefferink.areashop.listeners.SignBreakListener;
import me.wiefferink.areashop.listeners.SignChangeListener;
import me.wiefferink.areashop.listeners.SignClickListener;
import me.wiefferink.areashop.managers.*;
import me.wiefferink.areashop.managers.CommandManager;
import me.wiefferink.areashop.managers.FeatureManager;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.managers.Manager;
import me.wiefferink.areashop.managers.SignLinkerManager;
import me.wiefferink.areashop.tools.Analytics;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
@ -39,8 +43,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Main class for the AreaShop plugin
* Contains methods to get parts of the plugins functionality and definitions for constants
* Main class for the AreaShop plugin.
* Contains methods to get parts of the plugins functionality and definitions for constants.
*/
public final class AreaShop extends JavaPlugin implements AreaShopInterface {
// Statically available instance
@ -62,25 +66,25 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
private Updater updater = null;
private boolean updateAvailable = false;
private boolean ready = false;
// Folders and file names
public static final String languageFolder = "lang";
public static final String schematicFolder = "schem";
public static final String schematicExtension = ".schematic";
public static final String schematicExtension = ".schematic";
public static final String regionsFolder = "regions";
public static final String groupsFile = "groups.yml";
public static final String defaultFile = "default.yml";
public static final String configFile = "config.yml";
public static final String configFileHidden = "hiddenConfig.yml";
public static final String versionFile = "versions";
// Euro tag for in the config
public static final String currencyEuro = "%euro%";
// Constants for handling file versions
public static final String versionFiles = "files";
public static final int versionFilesCurrent = 3;
// Keys for replacing parts of flags, commands, strings
public static final String tagPlayerName = "player";
public static final String tagPlayerUUID = "uuid";
@ -136,37 +140,39 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
public static AreaShop getInstance() {
return AreaShop.instance;
}
/**
* Called on start or reload of the server
* Called on start or reload of the server.
*/
public void onEnable() {
AreaShop.instance = this;
managers = new HashSet<>();
boolean error = false;
// Check if WorldGuard is present
String wgVersion = null;
String rawVersion = null;
int major = 0, minor = 0, fixes = 0;
int major = 0;
int minor = 0;
int fixes = 0;
Integer build = null;
Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard");
if (plugin == null || !(plugin instanceof WorldGuardPlugin)) {
if(plugin == null || !(plugin instanceof WorldGuardPlugin)) {
error("WorldGuard plugin is not present or has not loaded correctly");
error = true;
} else {
worldGuard = (WorldGuardPlugin)plugin;
// Get correct WorldGuardInterface (handles things that changed version to version)
} else {
worldGuard = (WorldGuardPlugin)plugin;
// Get correct WorldGuardInterface (handles things that changed version to version)
try {
rawVersion = worldGuard.getDescription().getVersion();
if(rawVersion.contains("-SNAPSHOT;")) {
String buildNumber = rawVersion.substring(rawVersion.indexOf("-SNAPSHOT;")+10, rawVersion.length());
String buildNumber = rawVersion.substring(rawVersion.indexOf("-SNAPSHOT;") + 10, rawVersion.length());
if(buildNumber.contains("-")) {
buildNumber = buildNumber.substring(0, buildNumber.indexOf("-"));
try {
build = Integer.parseInt(buildNumber);
} catch(NumberFormatException e) {
warn("Could not correctly parse the build of WorldGuard, raw version: "+rawVersion+", buildNumber: "+buildNumber);
warn("Could not correctly parse the build of WorldGuard, raw version: " + rawVersion + ", buildNumber: " + buildNumber);
}
}
}
@ -191,7 +197,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
fixes = Integer.parseInt(versionParts[2]);
}
} catch(NumberFormatException e) {
warn("Something went wrong while parsing WorldGuard version number: "+rawVersion);
warn("Something went wrong while parsing WorldGuard version number: " + rawVersion);
}
// Determine correct implementation to use
if(worldGuard.getDescription().getVersion().startsWith("5.")) {
@ -213,63 +219,63 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
// Load chosen implementation
try {
final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldGuardHandler"+wgVersion);
final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldGuardHandler" + wgVersion);
// Check if we have a NMSHandler class at that location.
if (WorldGuardInterface.class.isAssignableFrom(clazz)) { // Make sure it actually implements WorldGuardInterface
if(WorldGuardInterface.class.isAssignableFrom(clazz)) { // Make sure it actually implements WorldGuardInterface
worldGuardInterface = (WorldGuardInterface)clazz.getConstructor(AreaShopInterface.class).newInstance(this); // Set our handler
}
} catch (final Exception e) {
error("Could not load the handler for WorldGuard (tried to load "+wgVersion+"), report this problem to the author:"+ExceptionUtils.getStackTrace(e));
} catch(final Exception e) {
error("Could not load the handler for WorldGuard (tried to load " + wgVersion + "), report this problem to the author:" + ExceptionUtils.getStackTrace(e));
error = true;
wgVersion = null;
}
}
wgVersion = null;
}
}
// Check if WorldEdit is present
String weVersion = null;
plugin = getServer().getPluginManager().getPlugin("WorldEdit");
if (plugin == null || !(plugin instanceof WorldEditPlugin)) {
if(plugin == null || !(plugin instanceof WorldEditPlugin)) {
error("WorldEdit plugin is not present or has not loaded correctly");
error = true;
} else {
worldEdit = (WorldEditPlugin)plugin;
// Get correct WorldEditInterface (handles things that changed version to version)
if(worldEdit.getDescription().getVersion().startsWith("5.")) {
weVersion = "5";
} else {
weVersion = "6";
}
try {
final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldEditHandler"+weVersion);
} else {
worldEdit = (WorldEditPlugin)plugin;
// Get correct WorldEditInterface (handles things that changed version to version)
if(worldEdit.getDescription().getVersion().startsWith("5.")) {
weVersion = "5";
} else {
weVersion = "6";
}
try {
final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldEditHandler" + weVersion);
// Check if we have a NMSHandler class at that location.
if (WorldEditInterface.class.isAssignableFrom(clazz)) { // Make sure it actually implements WorldEditInterface
if(WorldEditInterface.class.isAssignableFrom(clazz)) { // Make sure it actually implements WorldEditInterface
worldEditInterface = (WorldEditInterface)clazz.getConstructor(AreaShopInterface.class).newInstance(this); // Set our handler
}
} catch (final Exception e) {
error("Could not load the handler for WorldEdit (tried to load "+weVersion+"), report this problem to the author: "+ExceptionUtils.getStackTrace(e));
} catch(final Exception e) {
error("Could not load the handler for WorldEdit (tried to load " + weVersion + "), report this problem to the author: " + ExceptionUtils.getStackTrace(e));
error = true;
weVersion = null;
}
}
weVersion = null;
}
}
// Check if Vault is present
if(getServer().getPluginManager().getPlugin("Vault") == null) {
// Check if Vault is present
if(getServer().getPluginManager().getPlugin("Vault") == null) {
error("Vault plugin is not present or has not loaded correctly");
error = true;
}
}
// Load all data from files and check versions
fileManager = new FileManager();
managers.add(fileManager);
error = error|!fileManager.loadFiles(false);
error = error | !fileManager.loadFiles(false);
// Print loaded version of WG and WE in debug
if(wgVersion != null) {
AreaShop.debug("Loaded WorldGuardHandler"+wgVersion+" (raw version: "+rawVersion+", major:"+major+", minor:"+minor+", fixes:"+fixes+", build:"+build+")");
if(wgVersion != null) {
AreaShop.debug("Loaded WorldGuardHandler" + wgVersion + " (raw version: " + rawVersion + ", major:" + major + ", minor:" + minor + ", fixes:" + fixes + ", build:" + build + ")");
}
if(weVersion != null) {
AreaShop.debug("Loaded WorldEditHandler" + weVersion);
}
if(weVersion != null) {
AreaShop.debug("Loaded WorldEditHandler" + weVersion);
}
setupLanguageManager();
@ -286,25 +292,25 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
getServer().getPluginManager().registerEvents(new PlayerLoginLogoutListener(this), this);
setupTasks();
// Startup the CommandManager (registers itself for the command)
// Startup the CommandManager (registers itself for the command)
commandManager = new CommandManager();
managers.add(commandManager);
// Create a signLinkerManager
signLinkerManager = new SignLinkerManager();
managers.add(signLinkerManager);
// Enable Metrics if config allows it
// Enable Metrics if config allows it
if(getConfig().getBoolean("sendStats")) {
Analytics.start();
}
Analytics.start();
}
// Register dynamic permission (things declared in config)
registerDynamicPermissions();
// Don't initialize the updatechecker if disabled in the config
if(getConfig().getBoolean("checkForUpdates")) {
// Don't initialize the updatechecker if disabled in the config
if(getConfig().getBoolean("checkForUpdates")) {
new BukkitRunnable() {
@Override
public void run() {
@ -313,16 +319,16 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debug("Result=" + updater.getResult().toString() + ", Latest=" + updater.getLatestName() + ", Type=" + updater.getLatestType());
updateAvailable = updater.getResult() == UpdateResult.UPDATE_AVAILABLE;
if(updateAvailable) {
AreaShop.info("Update from AreaShop V"+AreaShop.getInstance().getDescription().getVersion()+" to "+updater.getLatestName()+" available, get the latest version at http://dev.bukkit.org/bukkit-plugins/regionbuyandrent/");
AreaShop.info("Update from AreaShop V" + AreaShop.getInstance().getDescription().getVersion() + " to " + updater.getLatestName() + " available, get the latest version at http://dev.bukkit.org/bukkit-plugins/regionbuyandrent/");
new BukkitRunnable() {
@Override
public void run() {
for(Player player : Utils.getOnlinePlayers()) {
if(player.hasPermission("areashop.notifyupdate")) {
AreaShop.getInstance().message(player, "update-playerNotify", AreaShop.getInstance().getDescription().getVersion(), AreaShop.getInstance().getUpdater().getLatestName());
AreaShop.getInstance().message(player, "update-playerNotify", AreaShop.getInstance().getDescription().getVersion(), AreaShop.getInstance().getUpdater().getLatestName());
}
}
}
}
}.runTask(AreaShop.getInstance());
}
} catch(Exception e) {
@ -331,13 +337,13 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
updateAvailable = false;
}
}
}.runTaskAsynchronously(this);
}.runTaskAsynchronously(this);
}
}
}
/**
* Called on shutdown or reload of the server
* Called on shutdown or reload of the server.
*/
public void onDisable() {
@ -370,23 +376,23 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Indicates if the plugin is ready to be used
* Indicates if the plugin is ready to be used.
* @return true if the plugin is ready, false otherwise
*/
public boolean isReady() {
return ready;
}
/**
* Set if the plugin is ready to be used or not (not to be used from another plugin!)
* Set if the plugin is ready to be used or not (not to be used from another plugin!).
* @param ready Indicate if the plugin is ready to be used
*/
public void setReady(boolean ready) {
this.ready = ready;
}
/**
* Set if the plugin should output debug messages (loaded from config normally)
* Set if the plugin should output debug messages (loaded from config normally).
* @param debug Indicates if the plugin should output debug messages or not
*/
public void setDebug(boolean debug) {
@ -394,7 +400,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Setup a new LanguageManager
* Setup a new LanguageManager.
*/
private void setupLanguageManager() {
languageManager = new LanguageManager(
@ -405,57 +411,57 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
chatprefix
);
}
/**
* Set the chatprefix to use in the chat (loaded from config normally)
* Set the chatprefix to use in the chat (loaded from config normally).
* @param chatprefix The string to use in front of chat messages (supports formatting codes)
*/
public void setChatprefix(List<String> chatprefix) {
this.chatprefix = chatprefix;
}
/**
* Function to get the WorldGuard plugin
* Function to get the WorldGuard plugin.
* @return WorldGuardPlugin
*/
public WorldGuardPlugin getWorldGuard() {
return worldGuard;
return worldGuard;
}
/**
* Function to get WorldGuardInterface for version dependent things
* Function to get WorldGuardInterface for version dependent things.
* @return WorldGuardInterface
*/
public WorldGuardInterface getWorldGuardHandler() {
return this.worldGuardInterface;
}
/**
* Function to get the WorldEdit plugin
* Function to get the WorldEdit plugin.
* @return WorldEditPlugin
*/
public WorldEditPlugin getWorldEdit() {
return worldEdit;
return worldEdit;
}
/**
* Function to get WorldGuardInterface for version dependent things
* Function to get WorldGuardInterface for version dependent things.
* @return WorldGuardInterface
*/
public WorldEditInterface getWorldEditHandler() {
return this.worldEditInterface;
}
/**
* Function to get the LanguageManager
* Function to get the LanguageManager.
* @return the LanguageManager
*/
public LanguageManager getLanguageManager() {
return languageManager;
return languageManager;
}
/**
* Function to get the CommandManager
* Function to get the CommandManager.
* @return the CommandManager
*/
public CommandManager getCommandManager() {
@ -463,8 +469,8 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Get the SignLinkerManager
* Handles sign linking mode
* Get the SignLinkerManager.
* Handles sign linking mode.
* @return The SignLinkerManager
*/
public SignLinkerManager getSignlinkerManager() {
@ -472,8 +478,8 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Get the FeatureManager
* Manages region specific features
* Get the FeatureManager.
* Manages region specific features.
* @return The FeatureManager
*/
public FeatureManager getFeatureManager() {
@ -481,44 +487,44 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Function to get the Vault plugin
* Function to get the Vault plugin.
* @return Economy
*/
public Economy getEconomy() {
RegisteredServiceProvider<Economy> economy = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economy == null || economy.getProvider() == null) {
if(economy == null || economy.getProvider() == null) {
error("There is no economy provider to support Vault, make sure you installed an economy plugin");
return null;
}
return economy.getProvider();
}
return economy.getProvider();
}
/**
* Method to get the FileManager (loads/save regions and can be used to get regions)
* Method to get the FileManager (loads/save regions and can be used to get regions).
* @return The fileManager
*/
public FileManager getFileManager() {
return fileManager;
}
/**
* Get the updater (check the update result)
* Get the updater (check the update result).
* @return The updater
*/
public Updater getUpdater() {
return updater;
}
/**
* Check if an update for AreaShop is available
* Check if an update for AreaShop is available.
* @return true if an update is available, otherwise false
*/
public boolean updateAvailable() {
return updateAvailable;
}
/**
* Register dynamic permissions controlled by config settings
* Register dynamic permissions controlled by config settings.
*/
private void registerDynamicPermissions() {
// Register limit groups of amount of regions a player can have
@ -532,22 +538,22 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
try {
Bukkit.getPluginManager().addPermission(perm);
} catch(IllegalArgumentException e) {
warn("Could not add the following permission to be used as limit: "+perm.getName());
warn("Could not add the following permission to be used as limit: " + perm.getName());
}
}
}
}
Bukkit.getPluginManager().recalculatePermissionDefaults(Bukkit.getPluginManager().getPermission("playerwarps.limits"));
}
/**
* Register all required tasks
* Register all required tasks.
*/
private void setupTasks() {
// Rent expiration timer
private void setupTasks() {
// Rent expiration timer
long expirationCheck = Utils.millisToTicks(Utils.getDurationFromSecondsOrString("expiration.delay"));
final AreaShop finalPlugin = this;
if(expirationCheck > 0) {
new BukkitRunnable() {
new BukkitRunnable() {
@Override
public void run() {
if(isReady()) {
@ -557,9 +563,9 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debugTask("Skipped checking rent expirations, plugin not ready");
}
}
}.runTaskTimer(this, 1, expirationCheck);
}
// Inactive unrenting/selling timer
}.runTaskTimer(this, 1, expirationCheck);
}
// Inactive unrenting/selling timer
long inactiveCheck = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("inactive.delay"));
if(inactiveCheck > 0) {
new BukkitRunnable() {
@ -572,9 +578,9 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debugTask("Skipped checking for regions of inactive players, plugin not ready");
}
}
}.runTaskTimer(this, inactiveCheck, inactiveCheck);
}
// Periodic updating of signs for timeleft tags
}.runTaskTimer(this, inactiveCheck, inactiveCheck);
}
// Periodic updating of signs for timeleft tags
long periodicUpdate = Utils.millisToTicks(Utils.getDurationFromSecondsOrString("signs.delay"));
if(periodicUpdate > 0) {
new BukkitRunnable() {
@ -587,9 +593,9 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debugTask("Skipped performing periodic sign update, plugin not ready");
}
}
}.runTaskTimer(this, periodicUpdate, periodicUpdate);
}
// Saving regions and group settings
}.runTaskTimer(this, periodicUpdate, periodicUpdate);
}
// Saving regions and group settings
long saveFiles = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("saving.delay"));
if(saveFiles > 0) {
new BukkitRunnable() {
@ -602,9 +608,9 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debugTask("Skipped saving required files, plugin not ready");
}
}
}.runTaskTimer(this, saveFiles, saveFiles);
}
// Sending warnings about rent regions to online players
}.runTaskTimer(this, saveFiles, saveFiles);
}
// Sending warnings about rent regions to online players
long expireWarning = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("expireWarning.delay"));
if(expireWarning > 0) {
new BukkitRunnable() {
@ -617,22 +623,22 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
AreaShop.debugTask("Skipped sending rent expire warnings, plugin not ready");
}
}
}.runTaskTimer(this, expireWarning, expireWarning);
}
// Update all regions on startup
if(getConfig().getBoolean("updateRegionsOnStartup")) {
new BukkitRunnable() {
}.runTaskTimer(this, expireWarning, expireWarning);
}
// Update all regions on startup
if(getConfig().getBoolean("updateRegionsOnStartup")) {
new BukkitRunnable() {
@Override
public void run() {
finalPlugin.getFileManager().updateAllRegions();
AreaShop.debugTask("Updating all regions at startup...");
}
}.runTaskLater(this, 20L);
}
}.runTaskLater(this, 20L);
}
}
/**
* Send a message to a target without a prefix
* Send a message to a target without a prefix.
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
@ -642,7 +648,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Send a message to a target, prefixed by the default chat prefix
* Send a message to a target, prefixed by the default chat prefix.
* @param target The target to send the message to
* @param key The key of the language string
* @param replacements The replacements to insert in the message
@ -651,9 +657,9 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
Message.fromKey(key).prefix().replacements(replacements).send(target);
}
/**
* Return the config
* Return the config.
*/
@Override
public YamlConfiguration getConfig() {
@ -661,23 +667,24 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Sends an debug message to the console
* Sends an debug message to the console.
* @param message The message that should be printed to the console
*/
public static void debug(Object... message) {
if(AreaShop.getInstance().debug) {
info("Debug: "+StringUtils.join(message, " "));
info("Debug: " + StringUtils.join(message, " "));
}
}
/**
* Non-static debug to use as implementation of the interface
* Non-static debug to use as implementation of the interface.
*/
public void debugI(Object... message) {
AreaShop.debug(StringUtils.join(message, " "));
}
/**
* Print an information message to the console
* Print an information message to the console.
* @param message The message to print
*/
public static void info(Object... message) {
@ -685,7 +692,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Print a warning to the console
* Print a warning to the console.
* @param message The message to print
*/
public static void warn(Object... message) {
@ -693,7 +700,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Print an error to the console
* Print an error to the console.
* @param message The messagfe to print
*/
public static void error(Object... message) {
@ -701,7 +708,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Print debug message for periodic task
* Print debug message for periodic task.
* @param message The message to print
*/
public static void debugTask(Object... message) {
@ -711,9 +718,8 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
}
/**
* Reload all files of the plugin and update all regions
* confirmationReceiver The CommandSender that should receive confirmation messages, null for nobody
* @param confirmationReceiver The CommandSender which should be notified when complete
* Reload all files of the plugin and update all regions.
* @param confirmationReceiver The CommandSender which should be notified when complete, null for nobody
*/
public void reload(final CommandSender confirmationReceiver) {
setReady(false);
@ -724,13 +730,14 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
fileManager.checkRents();
fileManager.updateAllRegions(confirmationReceiver);
}
/**
* Reload all files of the plugin and update all regions
* Reload all files of the plugin and update all regions.
*/
public void reload() {
reload(null);
}
}

View File

@ -19,12 +19,12 @@ import java.util.List;
import java.util.TreeSet;
public class AddCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop add";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.createrent") || target.hasPermission("areashop.createbuy")) {
@ -35,17 +35,17 @@ public class AddCommand extends CommandAreaShop {
@Override
public void execute(final CommandSender sender, final String[] args) {
if( !sender.hasPermission("areashop.createrent")
if(!sender.hasPermission("areashop.createrent")
&& !sender.hasPermission("areashop.createrent.member")
&& !sender.hasPermission("areashop.createrent.owner")
&& !sender.hasPermission("areashop.createbuy")
&& !sender.hasPermission("areashop.createbuy.member")
&& !sender.hasPermission("areashop.createbuy.owner")) {
plugin.message(sender, "add-noPermission");
return;
}
if(args.length < 2 || args[1] == null || (!"rent".equals(args[1].toLowerCase()) && !"buy".equals(args[1].toLowerCase()))) {
plugin.message(sender, "add-help");
return;
@ -60,14 +60,14 @@ public class AddCommand extends CommandAreaShop {
if(player == null) {
plugin.message(sender, "cmd-weOnlyByPlayer");
return;
}
}
Selection selection = plugin.getWorldEdit().getSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
world = selection.getWorld();
regions = Utils.getWERegionsInSelection(selection);
regions = Utils.getWorldEditRegionsInSelection(selection);
if(regions.size() == 0) {
plugin.message(player, "cmd-noWERegionsFound");
return;
@ -107,16 +107,16 @@ public class AddCommand extends CommandAreaShop {
final Player finalPlayer = player;
final World finalWorld = world;
AreaShop.debug("Starting add task with " + regions.size() + " regions");
new BukkitRunnable() {
new BukkitRunnable() {
private int current = 0;
private TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
private TreeSet<GeneralRegion> regionsAlready = new TreeSet<>();
private TreeSet<String> namesBlacklisted = new TreeSet<>();
private TreeSet<String> namesNoPermission = new TreeSet<>();
@Override
@Override
public void run() {
for(int i=0; i<plugin.getConfig().getInt("adding.regionsPerTick"); i++) {
for(int i = 0; i < plugin.getConfig().getInt("adding.regionsPerTick"); i++) {
if(current < finalRegions.size()) {
ProtectedRegion region = finalRegions.get(current);
// Determine if the player is an owner or member of the region
@ -138,7 +138,7 @@ public class AddCommand extends CommandAreaShop {
} else {
// Check if the player should be landlord
boolean landlord = (!sender.hasPermission("areashop.create" + type)
&& ((sender.hasPermission("areashop.create" + type + ".owner") && isOwner)
&& ((sender.hasPermission("areashop.create" + type + ".owner") && isOwner)
|| (sender.hasPermission("areashop.create" + type + ".member") && isMember)));
if(isRent) {
RentRegion rent = new RentRegion(region.getId(), finalWorld);
@ -164,7 +164,7 @@ public class AddCommand extends CommandAreaShop {
}
// Run commands
buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
plugin.getFileManager().addBuy(buy);
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
@ -195,9 +195,9 @@ public class AddCommand extends CommandAreaShop {
this.cancel();
}
}
}.runTaskTimer(plugin, 1, 1);
}.runTaskTimer(plugin, 1, 1);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -13,7 +13,7 @@ import java.util.ArrayList;
import java.util.List;
public class AddfriendCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop addfriend";
@ -26,7 +26,7 @@ public class AddfriendCommand extends CommandAreaShop {
}
return null;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
@ -34,7 +34,7 @@ public class AddfriendCommand extends CommandAreaShop {
plugin.message(sender, "addfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "addfriend-help");
return;
@ -42,13 +42,13 @@ public class AddfriendCommand extends CommandAreaShop {
GeneralRegion region;
if(args.length <= 2) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -57,7 +57,7 @@ public class AddfriendCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
@ -66,11 +66,11 @@ public class AddfriendCommand extends CommandAreaShop {
}
}
if(sender.hasPermission("areashop.addfriendall")) {
if ((region instanceof RentRegion && !((RentRegion) region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion) region).isSold())) {
plugin.message(sender, "addfriend-noOwner", region);
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "addfriend-noOwner", region);
return;
}
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
@ -117,7 +117,7 @@ public class AddfriendCommand extends CommandAreaShop {
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -16,12 +16,12 @@ import java.util.List;
import java.util.Set;
public class AddsignCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop addsign";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.addsign")) {
@ -35,11 +35,11 @@ public class AddsignCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.addsign")) {
plugin.message(sender, "addsign-noPermission");
return;
}
if (!(sender instanceof Player)) {
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
}
Player player = (Player)sender;
// Get the sign
@ -63,10 +63,10 @@ public class AddsignCommand extends CommandAreaShop {
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
return;
}
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getASRegionsInSelection(new CuboidSelection(block.getWorld(), block.getLocation(), block.getLocation()));
List<GeneralRegion> regions = Utils.getRegionsInSelection(new CuboidSelection(block.getWorld(), block.getLocation(), block.getLocation()));
if(regions.isEmpty()) {
plugin.message(sender, "addsign-noRegions");
return;
@ -100,7 +100,7 @@ public class AddsignCommand extends CommandAreaShop {
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -9,7 +9,7 @@ import java.util.ArrayList;
import java.util.List;
public class BuyCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop buy";
@ -22,14 +22,14 @@ public class BuyCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.buy")) {
plugin.message(sender, "buy-noPermission");
return;
}
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
@ -43,10 +43,10 @@ public class BuyCommand extends CommandAreaShop {
}
} else {
// get the region by location
List<BuyRegion> regions = Utils.getApplicableBuyRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).buy(player);

View File

@ -8,16 +8,16 @@ import java.util.ArrayList;
import java.util.List;
/**
* Abstract class for generalising command classes
* Abstract class for generalising command classes.
*/
public abstract class CommandAreaShop {
AreaShop plugin = AreaShop.getInstance();
/**
* Check if this Command instance can execute the given command and arguments
* Check if this Command instance can execute the given command and arguments.
* @param command The command to check for execution
* @param args The arguments to check
* @param args The arguments to check
* @return true if it can execute the command, false otherwise
*/
public boolean canExecute(Command command, String[] args) {
@ -30,38 +30,37 @@ public abstract class CommandAreaShop {
}
return commandString.toLowerCase().startsWith(getCommandStart().toLowerCase());
}
/**
* Get a list of string to complete a command with (raw list, not matching ones not filtered out)
* Get a list of string to complete a command with (raw list, not matching ones not filtered out).
* @param toComplete The number of the argument that has to be completed
* @param start The already given start of the command
* @param sender The CommandSender that wants to tab complete
* @param start The already given start of the command
* @param sender The CommandSender that wants to tab complete
* @return A collection with all the possibilities for argument to complete
*/
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
return new ArrayList<>();
}
/**
* Get the argument that comes after the base command that this command reacts to
* Get the argument that comes after the base command that this command reacts to.
* @return The string that should be in front of the command for this class to act
*/
public abstract String getCommandStart();
/**
* Returns the correct help string key to be used on the help page
* Returns the correct help string key to be used on the help page.
* @param target The CommandSender that the help message is for
* @return The help message key according to the permissions of the reciever
*/
public abstract String getHelp(CommandSender target);
/**
* Execute a (sub)command if the conditions are met
* Execute a (sub)command if the conditions are met.
* @param sender The commandSender that executed the command
* @param args The arguments that are given
* @param args The arguments that are given
*/
public abstract void execute(CommandSender sender, String[] args);
}

View File

@ -13,12 +13,12 @@ import java.util.List;
import java.util.TreeSet;
public class DelCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop del";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.destroyrent") || target.hasPermission("areashop.destroybuy")) {
@ -29,9 +29,9 @@ public class DelCommand extends CommandAreaShop {
@Override
public void execute(CommandSender sender, String[] args) {
if( !sender.hasPermission("areashop.destroybuy")
if(!sender.hasPermission("areashop.destroybuy")
&& !sender.hasPermission("areashop.destroybuy.landlord")
&& !sender.hasPermission("areashop.destroyrent")
&& !sender.hasPermission("areashop.destroyrent.landlord")) {
plugin.message(sender, "del-noPermission");
@ -48,8 +48,8 @@ public class DelCommand extends CommandAreaShop {
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getASRegionsInSelection(selection);
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions == null || regions.size() == 0) {
plugin.message(player, "cmd-noRegionsFound");
return;
@ -59,15 +59,15 @@ public class DelCommand extends CommandAreaShop {
TreeSet<GeneralRegion> namesFailed = new TreeSet<>();
for(GeneralRegion region : regions) {
boolean isLandlord = region.isLandlord(((Player)sender).getUniqueId());
if (region instanceof RentRegion) {
if(!sender.hasPermission("areashop.destroyrent") && !(isLandlord && sender.hasPermission("areashop.destroyrent.landlord"))) {
if(region instanceof RentRegion) {
if(!sender.hasPermission("areashop.destroyrent") && !(isLandlord && sender.hasPermission("areashop.destroyrent.landlord"))) {
namesFailed.add(region);
} else {
plugin.getFileManager().removeRent((RentRegion)region, true);
namesSuccess.add(region.getName());
}
} else if (region instanceof BuyRegion) {
if(!sender.hasPermission("areashop.destroybuy") && !(isLandlord && sender.hasPermission("areashop.destroybuy.landlord"))) {
} else if(region instanceof BuyRegion) {
if(!sender.hasPermission("areashop.destroybuy") && !(isLandlord && sender.hasPermission("areashop.destroybuy.landlord"))) {
namesFailed.add(region);
} else {
plugin.getFileManager().removeBuy((BuyRegion)region, true);
@ -89,16 +89,16 @@ public class DelCommand extends CommandAreaShop {
return;
}
boolean isLandlord = sender instanceof Player && region.isLandlord(((Player)sender).getUniqueId());
if (region instanceof RentRegion) {
// Remove the rent if the player has permission
if(region instanceof RentRegion) {
// Remove the rent if the player has permission
if(sender.hasPermission("areashop.destroyrent") || (isLandlord && sender.hasPermission("areashop.destroyrent.landlord"))) {
plugin.getFileManager().removeRent((RentRegion)region, true);
plugin.message(sender, "shutdown-successRent", region);
} else {
plugin.message(sender, "shutdown-noPermissionRent", region);
}
} else if (region instanceof BuyRegion) {
// Remove the buy if the player has permission
} else if(region instanceof BuyRegion) {
// Remove the buy if the player has permission
if(sender.hasPermission("areashop.destroybuy") || (isLandlord && sender.hasPermission("areashop.destroybuy.landlord"))) {
plugin.getFileManager().removeBuy((BuyRegion)region, true);
plugin.message(sender, "shutdown-successBuy", region);
@ -108,7 +108,7 @@ public class DelCommand extends CommandAreaShop {
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -28,7 +28,7 @@ public class DelfriendCommand extends CommandAreaShop {
}
/**
* Check if a person can remove friends
* Check if a person can remove friends.
* @param person The person to check
* @param region The region to check for
* @return true if the person can remove friends, otherwise false
@ -43,27 +43,27 @@ public class DelfriendCommand extends CommandAreaShop {
}
return false;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.delfriend") && !sender.hasPermission("areashop.delfriendall")) {
plugin.message(sender, "delfriend-noPermission");
return;
}
}
if(args.length < 2) {
plugin.message(sender, "delfriend-help");
return;
}
GeneralRegion region;
if(args.length <= 2) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -72,7 +72,7 @@ public class DelfriendCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
@ -81,11 +81,11 @@ public class DelfriendCommand extends CommandAreaShop {
}
}
if(sender.hasPermission("areashop.delfriendall")) {
if ((region instanceof RentRegion && !((RentRegion) region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion) region).isSold())) {
plugin.message(sender, "delfriend-noOwner", region);
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "delfriend-noOwner", region);
return;
}
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
@ -115,7 +115,7 @@ public class DelfriendCommand extends CommandAreaShop {
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -11,12 +11,12 @@ import java.util.ArrayList;
import java.util.List;
public class DelsignCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop delsign";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.delsign")) {
@ -31,10 +31,10 @@ public class DelsignCommand extends CommandAreaShop {
plugin.message(sender, "delsign-noPermission");
return;
}
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
}
Player player = (Player)sender;
// Get the sign
@ -58,7 +58,7 @@ public class DelsignCommand extends CommandAreaShop {
plugin.message(sender, "delsign-success", regionSign.getRegion());
regionSign.remove();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
return new ArrayList<>();

View File

@ -13,12 +13,12 @@ import java.util.List;
import java.util.Random;
public class FindCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop find";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.find")) {
@ -32,11 +32,11 @@ public class FindCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.find")) {
plugin.message(sender, "find-noPermission");
return;
}
if (!(sender instanceof Player)) {
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
}
if(args.length <= 1 || args[1] == null || (!args[1].equalsIgnoreCase("buy") && !args[1].equalsIgnoreCase("rent"))) {
plugin.message(sender, "find-help");
return;
@ -73,7 +73,7 @@ public class FindCommand extends CommandAreaShop {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
List<BuyRegion> results = new ArrayList<>();
for(BuyRegion region : regions) {
if(!region.isSold()
if(!region.isSold()
&& ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))
&& (group == null || group.isMember(region))
&& (region.getBooleanSetting("general.findCrossWorld") || player.getWorld().equals(region.getWorld()))) {
@ -113,7 +113,7 @@ public class FindCommand extends CommandAreaShop {
List<RentRegion> regions = plugin.getFileManager().getRents();
List<RentRegion> results = new ArrayList<>();
for(RentRegion region : regions) {
if(!region.isRented()
if(!region.isRented()
&& ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))
&& (group == null || group.isMember(region))
&& (region.getBooleanSetting("general.findCrossWorld") || player.getWorld().equals(region.getWorld()))) {
@ -149,7 +149,7 @@ public class FindCommand extends CommandAreaShop {
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -12,12 +12,12 @@ import java.util.List;
import java.util.TreeSet;
public class GroupaddCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupadd";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupadd")) {
@ -31,11 +31,11 @@ public class GroupaddCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.groupadd")) {
plugin.message(sender, "groupadd-noPermission");
return;
}
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupadd-help");
return;
}
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
group = new RegionGroup(plugin, args[1]);
@ -52,7 +52,7 @@ public class GroupaddCommand extends CommandAreaShop {
plugin.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getASRegionsInSelection(selection);
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) {
plugin.message(player, "cmd-noRegionsFound");
return;
@ -88,14 +88,14 @@ public class GroupaddCommand extends CommandAreaShop {
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
result = plugin.getFileManager().getRegionNames();
}
return result;
}

View File

@ -12,12 +12,12 @@ import java.util.List;
import java.util.TreeSet;
public class GroupdelCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupdel";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupdel")) {
@ -31,11 +31,11 @@ public class GroupdelCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.groupdel")) {
plugin.message(sender, "groupdel-noPermission");
return;
}
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupdel-help");
return;
}
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
group = new RegionGroup(plugin, args[1]);
@ -52,7 +52,7 @@ public class GroupdelCommand extends CommandAreaShop {
plugin.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getASRegionsInSelection(selection);
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) {
plugin.message(player, "cmd-noRegionsFound");
return;
@ -80,7 +80,7 @@ public class GroupdelCommand extends CommandAreaShop {
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(group.removeMember(region)) {
region.update();
plugin.message(sender, "groupdel-success", group.getName(), group.getMembers().size(), region);
@ -89,12 +89,12 @@ public class GroupdelCommand extends CommandAreaShop {
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}

View File

@ -13,7 +13,7 @@ public class GroupinfoCommand extends CommandAreaShop {
public String getCommandStart() {
return "areashop groupinfo";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupinfo")) {
@ -28,11 +28,11 @@ public class GroupinfoCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.groupinfo")) {
plugin.message(sender, "groupinfo-noPermission");
return;
}
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupinfo-help");
return;
}
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
plugin.message(sender, "groupinfo-noGroup", args[1]);
@ -45,7 +45,7 @@ public class GroupinfoCommand extends CommandAreaShop {
plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members));
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -7,12 +7,12 @@ import java.util.ArrayList;
import java.util.List;
public class GrouplistCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop grouplist";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.grouplist")) {
@ -34,7 +34,7 @@ public class GrouplistCommand extends CommandAreaShop {
plugin.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups));
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
return new ArrayList<>();

View File

@ -3,12 +3,12 @@ package me.wiefferink.areashop.commands;
import org.bukkit.command.CommandSender;
public class HelpCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop help";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.help")) {

View File

@ -10,7 +10,14 @@ import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class InfoCommand extends CommandAreaShop {
@ -28,17 +35,17 @@ public class InfoCommand extends CommandAreaShop {
}
/**
* Display a page of a list of regions
* @param sender The CommandSender to send the messages to
* @param regions The regions to display
* Display a page of a list of regions.
* @param sender The CommandSender to send the messages to
* @param regions The regions to display
* @param filterGroup The group to filter the regions by
* @param keyHeader The header to print above the page
* @param pageInput The page number, if any
* @param keyHeader The header to print above the page
* @param pageInput The page number, if any
* @param baseCommand The command to execute for next/previous page
*/
private void showSortedPagedList(CommandSender sender, List<? extends GeneralRegion> regions, RegionGroup filterGroup, String keyHeader, String pageInput, String baseCommand) {
int MAX_ITEMS = 20;
int ITEMS_PER_PAGE = MAX_ITEMS-2;
int maximumItems = 20;
int itemsPerPage = maximumItems - 2;
int page = 1;
if(pageInput != null && Utils.isNumeric(pageInput)) {
try {
@ -77,14 +84,14 @@ public class InfoCommand extends CommandAreaShop {
}
plugin.message(sender, keyHeader, limitedToGroup);
// Page entries
int totalPages = (int)Math.ceil(regions.size()/(double)ITEMS_PER_PAGE); // Clip page to correct boundaries, not much need to tell the user
if(regions.size() == ITEMS_PER_PAGE+1) { // 19 total items is mapped to 1 page of 19
ITEMS_PER_PAGE++;
int totalPages = (int)Math.ceil(regions.size() / (double)itemsPerPage); // Clip page to correct boundaries, not much need to tell the user
if(regions.size() == itemsPerPage + 1) { // 19 total items is mapped to 1 page of 19
itemsPerPage++;
totalPages = 1;
}
page = Math.max(1, Math.min(totalPages, page));
int linesPrinted = 1; // header
for(int i = (page-1)*ITEMS_PER_PAGE; i < page*ITEMS_PER_PAGE && i < regions.size(); i++) {
for(int i = (page - 1) * itemsPerPage; i < page * itemsPerPage && i < regions.size(); i++) {
String state;
GeneralRegion region = regions.get(i);
if(region.getType() == GeneralRegion.RegionType.RENT) {
@ -102,30 +109,30 @@ public class InfoCommand extends CommandAreaShop {
state = "Reselling";
}
}
plugin.messageNoPrefix(sender, "info-entry"+state, region);
plugin.messageNoPrefix(sender, "info-entry" + state, region);
linesPrinted++;
}
Message footer = Message.empty();
// Previous button
if(page > 1) {
footer.append(Message.fromKey("info-pagePrevious").replacements(baseCommand+" "+(page-1)));
footer.append(Message.fromKey("info-pagePrevious").replacements(baseCommand + " " + (page - 1)));
} else {
footer.append(Message.fromKey("info-pageNoPrevious"));
}
// Page status
if(totalPages > 1) {
String pageString = ""+page;
for(int i = pageString.length(); i < (totalPages+"").length(); i++) {
pageString = "0"+pageString;
String pageString = "" + page;
for(int i = pageString.length(); i < (totalPages + "").length(); i++) {
pageString = "0" + pageString;
}
footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages));
if(page < totalPages) {
footer.append(Message.fromKey("info-pageNext").replacements(baseCommand+" "+(page+1)));
footer.append(Message.fromKey("info-pageNext").replacements(baseCommand + " " + (page + 1)));
} else {
footer.append(Message.fromKey("info-pageNoNext"));
}
// Fill up space if the page is not full (aligns header nicely)
for(int i = linesPrinted; i < MAX_ITEMS-1; i++) {
for(int i = linesPrinted; i < maximumItems - 1; i++) {
sender.sendMessage(" ");
}
footer.send(sender);
@ -134,7 +141,7 @@ public class InfoCommand extends CommandAreaShop {
}
/**
* Get an integer to order by type, usable for Comparators
* Get an integer to order by type, usable for Comparators.
* @param region The region to get the order for
* @return An integer for sorting by type
*/
@ -155,7 +162,7 @@ public class InfoCommand extends CommandAreaShop {
}
}
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.info")) {
@ -179,12 +186,12 @@ public class InfoCommand extends CommandAreaShop {
}
}
}
// All regions
if(args[1].equalsIgnoreCase("all")) {
showSortedPagedList(sender, plugin.getFileManager().getRegions(), filterGroup, "info-allHeader", (args.length > 2 ? args[2] : null), "/areashop info all");
}
// Rented regions
else if(args[1].equalsIgnoreCase("rented")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
@ -258,20 +265,20 @@ public class InfoCommand extends CommandAreaShop {
rent = plugin.getFileManager().getRent(args[2]);
buy = plugin.getFileManager().getBuy(args[2]);
} else {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
if (regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if (regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
if(regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if(regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
}
}
} else {
@ -279,12 +286,12 @@ public class InfoCommand extends CommandAreaShop {
return;
}
}
if(rent == null && buy == null) {
plugin.message(sender, "info-regionNotExisting", args[2]);
return;
}
}
if(rent != null) {
plugin.message(sender, "info-regionHeaderRent", rent);
if(rent.isRented()) {
@ -320,12 +327,12 @@ public class InfoCommand extends CommandAreaShop {
plugin.messageNoPrefix(sender, "info-regionMaxExtends", rent);
}
}
// If maxExtends is zero it does not make sense to show this message
if (rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
plugin.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
// If maxExtends is zero it does not make sense to show this message
if(rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
plugin.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
}
if(rent.getInactiveTimeUntilUnrent() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
plugin.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
@ -400,7 +407,7 @@ public class InfoCommand extends CommandAreaShop {
plugin.messageNoPrefix(sender, "info-regionLandlord", buy);
}
if(buy.getInactiveTimeUntilSell() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveSell", buy);
plugin.messageNoPrefix(sender, "info-regionInactiveSell", buy);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
@ -454,9 +461,9 @@ public class InfoCommand extends CommandAreaShop {
}
} else {
plugin.message(sender, "info-help");
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -9,12 +9,12 @@ import java.util.List;
import java.util.Set;
public class LinksignsCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop linksigns";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.linksigns")) {
@ -28,12 +28,12 @@ public class LinksignsCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.linksigns")) {
plugin.message(sender, "linksigns-noPermission");
return;
}
if (!(sender instanceof Player)) {
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(plugin.getSignlinkerManager().isInSignLinkMode(player)) {
plugin.getSignlinkerManager().exitSignLinkMode(player);
@ -58,7 +58,7 @@ public class LinksignsCommand extends CommandAreaShop {
plugin.getSignlinkerManager().enterSignLinkMode(player, profile);
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -15,7 +15,7 @@ import java.util.List;
import java.util.Set;
public class MeCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop me";
@ -28,7 +28,7 @@ public class MeCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.me")) {

View File

@ -43,8 +43,8 @@ public class MessageCommand extends CommandAreaShop {
return;
}
String[] messageArgs = new String[args.length-2];
System.arraycopy(args, 2, messageArgs, 0, args.length-2);
String[] messageArgs = new String[args.length - 2];
System.arraycopy(args, 2, messageArgs, 0, args.length - 2);
String message = StringUtils.join(messageArgs);
Message.fromString(message).send(player);

View File

@ -8,7 +8,7 @@ public class ReloadCommand extends CommandAreaShop {
public String getCommandStart() {
return "areashop reload";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.reload")) {

View File

@ -9,7 +9,7 @@ import java.util.ArrayList;
import java.util.List;
public class RentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop rent";
@ -22,17 +22,17 @@ public class RentCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.rent")) {
plugin.message(sender, "rent-noPermission");
return;
}
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
RentRegion rent = plugin.getFileManager().getRent(args[1]);
@ -43,17 +43,17 @@ public class RentCommand extends CommandAreaShop {
}
} else {
// get the region by location
List<RentRegion> regions = Utils.getApplicableRentRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).rent(player);
}
}
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -9,7 +9,7 @@ import java.util.ArrayList;
import java.util.List;
public class ResellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop resell";
@ -22,14 +22,14 @@ public class ResellCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.resell") && !sender.hasPermission("areashop.resellall")) {
plugin.message(sender, "resell-noPermissionOther");
return;
}
if(args.length <= 1) {
plugin.message(sender, "resell-help");
return;
@ -49,13 +49,13 @@ public class ResellCommand extends CommandAreaShop {
BuyRegion buy;
if(args.length <= 2) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getApplicableBuyRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -64,7 +64,7 @@ public class ResellCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
buy = plugin.getFileManager().getBuy(args[2]);
if(buy == null) {
@ -94,9 +94,9 @@ public class ResellCommand extends CommandAreaShop {
}
} else {
plugin.message(sender, "resell-noPermission", buy);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -24,18 +24,18 @@ public class SchematiceventCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.schematicevents")) {
plugin.message(sender, "schemevent-noPermission");
return;
}
if(args.length < 3 || args[1] == null || args[2] == null) {
plugin.message(sender, "schemevent-help");
return;
}
}
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
@ -50,7 +50,7 @@ public class SchematiceventCommand extends CommandAreaShop {
try {
event = GeneralRegion.RegionEvent.valueOf(args[2].toUpperCase());
} catch(IllegalArgumentException e) {
exception = true;
exception = true;
}
// Check for a totally wrong event or a non matching event
if(exception) {
@ -59,8 +59,8 @@ public class SchematiceventCommand extends CommandAreaShop {
values.add(value.getValue().toLowerCase());
}
plugin.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values), region);
return;
}
return;
}
region.handleSchematicEvent(event);
region.update();
plugin.message(sender, "schemevent-success", args[2], region);
@ -74,10 +74,10 @@ public class SchematiceventCommand extends CommandAreaShop {
} else if(toComplete == 3) {
GeneralRegion region = plugin.getFileManager().getRegion(start[2]);
if(region != null) {
if (region instanceof RentRegion) {
result.addAll(Arrays.asList("created", "deleted", "rented", "unrented"));
} else if (region instanceof BuyRegion) {
result.addAll(Arrays.asList("created", "deleted", "bought", "sold"));
if(region instanceof RentRegion) {
result.addAll(Arrays.asList("created", "deleted", "rented", "unrented"));
} else if(region instanceof BuyRegion) {
result.addAll(Arrays.asList("created", "deleted", "bought", "sold"));
}
}
}

View File

@ -25,7 +25,7 @@ public class SellCommand extends CommandAreaShop {
}
/**
* Check if a person can sell the region
* Check if a person can sell the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can sell it, otherwise false
@ -40,7 +40,7 @@ public class SellCommand extends CommandAreaShop {
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.sell") && !sender.hasPermission("areashop.sellown")) {
@ -49,13 +49,13 @@ public class SellCommand extends CommandAreaShop {
}
BuyRegion buy;
if(args.length <= 1) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getApplicableBuyRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -64,7 +64,7 @@ public class SellCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
}
@ -78,7 +78,7 @@ public class SellCommand extends CommandAreaShop {
}
buy.sell(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -14,7 +14,7 @@ public class SetdurationCommand extends CommandAreaShop {
public String getCommandStart() {
return "areashop setduration";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setduration")) {
@ -39,13 +39,13 @@ public class SetdurationCommand extends CommandAreaShop {
}
RentRegion rent;
if(args.length <= regionArgument) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getApplicableRentRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -54,7 +54,7 @@ public class SetdurationCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
rent = plugin.getFileManager().getRent(args[regionArgument]);
}
@ -65,7 +65,7 @@ public class SetdurationCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.setduration") && !(sender instanceof Player && rent.isLandlord(((Player)sender).getUniqueId()))) {
plugin.message(sender, "setduration-noLandlord", rent);
return;
}
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
rent.setDuration(null);
rent.update();
@ -78,15 +78,15 @@ public class SetdurationCommand extends CommandAreaShop {
plugin.message(sender, "setduration-wrongAmount", args[1], rent);
return;
}
if(!Utils.checkTimeFormat(args[1]+" "+args[2])) {
plugin.message(sender, "setduration-wrongFormat", args[1]+" "+args[2], rent);
if(!Utils.checkTimeFormat(args[1] + " " + args[2])) {
plugin.message(sender, "setduration-wrongFormat", args[1] + " " + args[2], rent);
return;
}
rent.setDuration(args[1]+" "+args[2]);
}
rent.setDuration(args[1] + " " + args[2]);
rent.update();
plugin.message(sender, "setduration-success", rent);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -11,12 +11,12 @@ import java.util.ArrayList;
import java.util.List;
public class SetlandlordCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setlandlord";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setlandlord")) {
@ -30,7 +30,7 @@ public class SetlandlordCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.setlandlord")) {
plugin.message(sender, "setlandlord-noPermission");
return;
}
}
if(args.length < 2) {
plugin.message(sender, "setlandlord-help");
return;
@ -39,13 +39,13 @@ public class SetlandlordCommand extends CommandAreaShop {
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
GeneralRegion region;
if(args.length < 3) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -54,14 +54,14 @@ public class SetlandlordCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
}
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
String playerName = player.getName();
if(playerName == null || playerName.isEmpty()) {
playerName = args[1];
@ -70,7 +70,7 @@ public class SetlandlordCommand extends CommandAreaShop {
region.update();
plugin.message(sender, "setlandlord-success", playerName, region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -15,7 +15,7 @@ import java.util.List;
import java.util.UUID;
public class SetownerCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setowner";
@ -28,7 +28,7 @@ public class SetownerCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setownerrent") && !sender.hasPermission("areashop.setownerbuy")) {
@ -39,15 +39,15 @@ public class SetownerCommand extends CommandAreaShop {
if(args.length < 2) {
plugin.message(sender, "setowner-help");
return;
}
}
if(args.length == 2) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -65,15 +65,15 @@ public class SetownerCommand extends CommandAreaShop {
return;
}
if (region instanceof RentRegion && !sender.hasPermission("areashop.setownerrent")) {
plugin.message(sender, "setowner-noPermissionRent", region);
if(region instanceof RentRegion && !sender.hasPermission("areashop.setownerrent")) {
plugin.message(sender, "setowner-noPermissionRent", region);
return;
}
if (region instanceof BuyRegion && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermissionBuy", region);
if(region instanceof BuyRegion && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermissionBuy", region);
return;
}
UUID uuid = null;
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
@ -85,8 +85,8 @@ public class SetownerCommand extends CommandAreaShop {
return;
}
if (region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isRenter(uuid)) {
// extend
Calendar calendar = Calendar.getInstance();
@ -100,8 +100,8 @@ public class SetownerCommand extends CommandAreaShop {
plugin.message(sender, "setowner-succesRent", region);
}
}
if (region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
if(region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
buy.setBuyer(uuid);
plugin.message(sender, "setowner-succesBuy", region);
}
@ -109,7 +109,7 @@ public class SetownerCommand extends CommandAreaShop {
region.update();
region.saveRequired();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -16,7 +16,7 @@ public class SetpriceCommand extends CommandAreaShop {
public String getCommandStart() {
return "areashop setprice";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setprice")) {
@ -30,20 +30,20 @@ public class SetpriceCommand extends CommandAreaShop {
if(!sender.hasPermission("areashop.setprice") && (!sender.hasPermission("areashop.setprice.landlord") && sender instanceof Player)) {
plugin.message(sender, "setprice-noPermission");
return;
}
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "setprice-help");
return;
}
GeneralRegion region;
if(args.length < 3) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -52,10 +52,10 @@ public class SetpriceCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
}
if(region == null) {
plugin.message(sender, "setprice-notRegistered", args[2]);
return;
@ -65,10 +65,10 @@ public class SetpriceCommand extends CommandAreaShop {
return;
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
if (region instanceof RentRegion) {
((RentRegion)region).removePrice();
} else if (region instanceof BuyRegion) {
((BuyRegion)region).removePrice();
if(region instanceof RentRegion) {
((RentRegion)region).removePrice();
} else if(region instanceof BuyRegion) {
((BuyRegion)region).removePrice();
}
region.update();
plugin.message(sender, "setprice-successRemoved", region);
@ -81,21 +81,21 @@ public class SetpriceCommand extends CommandAreaShop {
plugin.message(sender, "setprice-wrongPrice", args[1], region);
return;
}
if (region instanceof RentRegion) {
((RentRegion)region).setPrice(price);
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(price);
plugin.message(sender, "setprice-successRent", region);
} else if (region instanceof BuyRegion) {
((BuyRegion)region).setPrice(price);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(price);
plugin.message(sender, "setprice-successBuy", region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
result = plugin.getFileManager().getRegionNames();
}
return result;
}

View File

@ -7,12 +7,12 @@ import java.util.ArrayList;
import java.util.List;
public class SetrestoreCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setrestore";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setrestore")) {
@ -45,7 +45,7 @@ public class SetrestoreCommand extends CommandAreaShop {
region.setRestoreSetting(value);
String valueString = "general";
if(value != null) {
valueString = value+"";
valueString = value + "";
}
if(args.length > 3) {
region.setSchematicProfile(args[3]);
@ -55,7 +55,7 @@ public class SetrestoreCommand extends CommandAreaShop {
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -12,12 +12,12 @@ import java.util.ArrayList;
import java.util.List;
public class SetteleportCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop settp";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.teleportall") || target.hasPermission("areashop.teleport")) {
@ -27,7 +27,7 @@ public class SetteleportCommand extends CommandAreaShop {
}
/**
* Check if a person can set the teleport location of the region
* Check if a person can set the teleport location of the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can set the teleport location, otherwise false
@ -47,7 +47,7 @@ public class SetteleportCommand extends CommandAreaShop {
plugin.message(sender, "setteleport-noPermission");
return;
}
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "onlyByPlayer");
return;
}
@ -55,7 +55,7 @@ public class SetteleportCommand extends CommandAreaShop {
GeneralRegion region;
if(args.length < 2) {
// get the region by location
List<GeneralRegion> regions = Utils.getAllApplicableRegions(((Player)sender).getLocation());
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
@ -70,13 +70,13 @@ public class SetteleportCommand extends CommandAreaShop {
}
boolean owner;
if(region == null) {
plugin.message(player, "setteleport-noRentOrBuy", args[1]);
return;
}
if (region instanceof RentRegion) {
owner = player.getUniqueId().equals(((RentRegion)region).getRenter());
if(region instanceof RentRegion) {
owner = player.getUniqueId().equals(((RentRegion)region).getRenter());
} else {
owner = player.getUniqueId().equals(((BuyRegion)region).getBuyer());
}
@ -103,7 +103,7 @@ public class SetteleportCommand extends CommandAreaShop {
region.update();
plugin.message(player, "setteleport-success", region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -21,12 +21,12 @@ import java.util.ArrayList;
import java.util.List;
public class StackCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop stack";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.stack")) {
@ -43,7 +43,7 @@ public class StackCommand extends CommandAreaShop {
return;
}
// Only from ingame
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
@ -82,7 +82,7 @@ public class StackCommand extends CommandAreaShop {
if(selection == null) {
plugin.message(player, "stack-noSelection");
return;
}
}
// Get or create group
RegionGroup group = null;
if(args.length > 5) {
@ -94,28 +94,28 @@ public class StackCommand extends CommandAreaShop {
}
// Get facing of the player (must be clearly one of the four directions to make sure it is no mistake)
BlockFace facing = Utils.yawToFacing(player.getLocation().getYaw());
if (player.getLocation().getPitch() > 45) {
facing = BlockFace.DOWN;
} else if (player.getLocation().getPitch() < -45) {
facing = BlockFace.UP;
}
if (!(facing == BlockFace.NORTH || facing == BlockFace.EAST || facing == BlockFace.SOUTH || facing == BlockFace.WEST || facing == BlockFace.UP || facing == BlockFace.DOWN)) {
plugin.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
if(player.getLocation().getPitch() > 45) {
facing = BlockFace.DOWN;
} else if(player.getLocation().getPitch() < -45) {
facing = BlockFace.UP;
}
if(!(facing == BlockFace.NORTH || facing == BlockFace.EAST || facing == BlockFace.SOUTH || facing == BlockFace.WEST || facing == BlockFace.UP || facing == BlockFace.DOWN)) {
plugin.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
return;
}
Vector shift = new BlockVector(0, 0, 0);
if(facing == BlockFace.SOUTH) {
shift = shift.setZ(-selection.getLength()-gap);
shift = shift.setZ(-selection.getLength() - gap);
} else if(facing == BlockFace.WEST) {
shift = shift.setX(selection.getWidth()+gap);
shift = shift.setX(selection.getWidth() + gap);
} else if(facing == BlockFace.NORTH) {
shift = shift.setZ(selection.getLength()+gap);
shift = shift.setZ(selection.getLength() + gap);
} else if(facing == BlockFace.EAST) {
shift = shift.setX(-selection.getWidth()-gap);
} else if (facing == BlockFace.DOWN) {
shift = shift.setY(-selection.getHeight()-gap);
} else if (facing == BlockFace.UP) {
shift = shift.setY(selection.getHeight()+gap);
shift = shift.setX(-selection.getWidth() - gap);
} else if(facing == BlockFace.DOWN) {
shift = shift.setY(-selection.getHeight() - gap);
} else if(facing == BlockFace.UP) {
shift = shift.setY(selection.getHeight() + gap);
}
AreaShop.debug(" calculated shift vector: " + shift + ", with facing=" + facing);
// Create regions and add them to AreaShop
@ -134,34 +134,34 @@ public class StackCommand extends CommandAreaShop {
Message groupsMessage = Message.empty();
if(group != null) {
groupsMessage = Message.fromKey("stack-addToGroup").replacements(group.getName());
}
}
plugin.message(player, "stack-accepted", amount, type, gap, namePrefix, groupsMessage);
plugin.message(player, "stack-addStart", amount, regionsPerTick*20);
plugin.message(player, "stack-addStart", amount, regionsPerTick * 20);
new BukkitRunnable() {
private int current = -1;
private RegionManager manager = AreaShop.getInstance().getWorldGuard().getRegionManager(selection.getWorld());
private int current = -1;
private RegionManager manager = AreaShop.getInstance().getWorldGuard().getRegionManager(selection.getWorld());
private int counter = 1;
private int tooLow = 0;
private int tooHigh = 0;
private int tooLow = 0;
private int tooHigh = 0;
@Override
@Override
public void run() {
for(int i=0; i<regionsPerTick; i++) {
current++;
if(current < amount) {
for(int i = 0; i < regionsPerTick; i++) {
current++;
if(current < amount) {
// Create the region name
String counterName = counter+"";
String counterName = counter + "";
int minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName = "0"+counterName;
counterName = "0" + counterName;
}
String regionName = namePrefix + counterName;
while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) {
counter++;
counterName = counter+"";
counterName = counter + "";
minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName = "0"+counterName;
counterName = "0" + counterName;
}
regionName = namePrefix + counterName;
}
@ -169,15 +169,15 @@ public class StackCommand extends CommandAreaShop {
BlockVector minimum = new BlockVector(selection.getNativeMinimumPoint().add(finalShift.multiply(current)));
BlockVector maximum = new BlockVector(selection.getNativeMaximumPoint().add(finalShift.multiply(current)));
// Check for out of bounds
if (minimum.getBlockY() < 0) {
tooLow++;
continue;
} else if (maximum.getBlockY() > 256) {
tooHigh++;
continue;
}
ProtectedCuboidRegion region = new ProtectedCuboidRegion(regionName, minimum, maximum);
manager.addRegion(region);
if(minimum.getBlockY() < 0) {
tooLow++;
continue;
} else if(maximum.getBlockY() > 256) {
tooHigh++;
continue;
}
ProtectedCuboidRegion region = new ProtectedCuboidRegion(regionName, minimum, maximum);
manager.addRegion(region);
// Add the region to AreaShop
if(rentRegions) {
RentRegion rent = new RentRegion(region.getId(), selection.getWorld());
@ -200,26 +200,26 @@ public class StackCommand extends CommandAreaShop {
buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
buy.update();
}
}
}
}
}
if(current >= amount) {
if(player.isOnline()) {
int added = amount - tooLow - tooHigh;
int added = amount - tooLow - tooHigh;
Message wrong = Message.empty();
if(tooHigh > 0) {
wrong.append(Message.fromKey("stack-tooHigh").replacements(tooHigh));
}
if (tooLow > 0) {
wrong.append(Message.fromKey("stack-tooLow").replacements(tooLow));
}
plugin.message(player, "stack-addComplete", added, wrong);
}
}
if(tooLow > 0) {
wrong.append(Message.fromKey("stack-tooLow").replacements(tooLow));
}
plugin.message(player, "stack-addComplete", added, wrong);
}
this.cancel();
}
}
}.runTaskTimer(plugin, 1, 1);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -22,7 +22,7 @@ public class StopresellCommand extends CommandAreaShop {
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.stopresell") && !sender.hasPermission("areashop.stopresellall")) {
@ -32,13 +32,13 @@ public class StopresellCommand extends CommandAreaShop {
BuyRegion buy;
if(args.length <= 1) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getApplicableBuyRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -47,7 +47,7 @@ public class StopresellCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
if(buy == null) {
@ -77,9 +77,9 @@ public class StopresellCommand extends CommandAreaShop {
}
} else {
plugin.message(sender, "stopresell-noPermission", buy);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -8,12 +8,12 @@ import java.util.ArrayList;
import java.util.List;
public class TeleportCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop tp";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.teleportall") || target.hasPermission("areashop.teleport")) {
@ -23,7 +23,7 @@ public class TeleportCommand extends CommandAreaShop {
}
/**
* Check if a person can teleport to the region (assuming he is not teleporting to a sign)
* Check if a person can teleport to the region (assuming he is not teleporting to a sign).
* @param person The person to check
* @param region The region to check for
* @return true if the person can teleport to it, otherwise false
@ -45,10 +45,10 @@ public class TeleportCommand extends CommandAreaShop {
plugin.message(sender, "teleport-noPermission");
return;
}
if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
}
if(args.length <= 1 || args[1] == null) {
plugin.message(sender, "teleport-help");
return;
@ -66,7 +66,7 @@ public class TeleportCommand extends CommandAreaShop {
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -10,7 +10,7 @@ import java.util.ArrayList;
import java.util.List;
public class UnrentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop unrent";
@ -25,7 +25,7 @@ public class UnrentCommand extends CommandAreaShop {
}
/**
* Check if a person can unrent the region
* Check if a person can unrent the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can unrent it, otherwise false
@ -49,13 +49,13 @@ public class UnrentCommand extends CommandAreaShop {
}
RentRegion rent;
if(args.length <= 1) {
if (sender instanceof Player) {
if(sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getApplicableRentRegions(((Player) sender).getLocation());
if (regions.isEmpty()) {
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if (regions.size() > 1) {
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
@ -64,21 +64,21 @@ public class UnrentCommand extends CommandAreaShop {
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
} else {
rent = plugin.getFileManager().getRent(args[1]);
}
if(rent == null) {
plugin.message(sender, "unrent-notRegistered");
return;
}
}
if(!rent.isRented()) {
plugin.message(sender, "unrent-notRented", rent);
return;
}
rent.unRent(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();

View File

@ -10,7 +10,7 @@ public class CancellableRegionEvent<T> extends RegionEvent<T> {
}
/**
* Cancel the event from happening
* Cancel the event from happening.
* @param reason The reason of cancelling, used for display to the user, should end with a dot
*/
public void cancel(String reason) {
@ -19,7 +19,7 @@ public class CancellableRegionEvent<T> extends RegionEvent<T> {
}
/**
* Let the event continue, possible overwriting a cancel() call from another plugin
* Let the event continue, possible overwriting a cancel() call from another plugin.
*/
public void allow() {
this.cancelled = false;
@ -27,7 +27,7 @@ public class CancellableRegionEvent<T> extends RegionEvent<T> {
}
/**
* Check if the event has been cancelled
* Check if the event has been cancelled.
* @return true if the event has been cancelled, otherwise false
*/
public boolean isCancelled() {
@ -35,7 +35,7 @@ public class CancellableRegionEvent<T> extends RegionEvent<T> {
}
/**
* Get the reason why this event is cancelled
* Get the reason why this event is cancelled.
* @return null if there is no reason or the event is not cancelled, otherwise a string
*/
public String getReason() {

View File

@ -21,7 +21,7 @@ public class RegionEvent<T> extends Event {
}
/**
* Get the region of this event
* Get the region of this event.
* @return The region the event is about
*/
public T getRegion() {

View File

@ -12,7 +12,7 @@ public class BuyingRegionEvent extends CancellableRegionEvent<BuyRegion> {
private Player player;
/**
* Constructor
* Constructor.
* @param region The region that is about to get bought
* @param player The player that tries to buy the region
*/
@ -22,7 +22,7 @@ public class BuyingRegionEvent extends CancellableRegionEvent<BuyRegion> {
}
/**
* Get the player that is trying to buy the region
* Get the player that is trying to buy the region.
* @return The player that is trying to buy the region
*/
public Player getPlayer() {

View File

@ -5,7 +5,7 @@ import me.wiefferink.areashop.regions.RentRegion;
import org.bukkit.entity.Player;
/**
* Broadcasted when a player tries to rent a region
* Broadcasted when a player tries to rent a region.
*/
public class RentingRegionEvent extends CancellableRegionEvent<RentRegion> {
@ -13,7 +13,7 @@ public class RentingRegionEvent extends CancellableRegionEvent<RentRegion> {
private boolean extending;
/**
* Constructor
* Constructor.
* @param region The region that is about to be rented
* @param player The player that tries to rent the region
* @param extending true if the player is extending the rental of the region, otherwise false
@ -25,7 +25,7 @@ public class RentingRegionEvent extends CancellableRegionEvent<RentRegion> {
}
/**
* Get the player that is trying to rent the region
* Get the player that is trying to rent the region.
* @return The player that is trying to rent the region
*/
public Player getPlayer() {
@ -33,7 +33,7 @@ public class RentingRegionEvent extends CancellableRegionEvent<RentRegion> {
}
/**
* Check if the player is extending the region or renting it for the first time
* Check if the player is extending the region or renting it for the first time.
* @return true if the player tries to extend the region, false if he tries to rent it the first time
*/
public boolean isExtending() {

View File

@ -5,14 +5,14 @@ import me.wiefferink.areashop.regions.BuyRegion;
import org.bukkit.entity.Player;
/**
* Broadcasted when a player tries to resell a region
* Broadcasted when a player tries to resell a region.
*/
public class ResellingRegionEvent extends CancellableRegionEvent<BuyRegion> {
private Player player;
/**
* Contructor
* Contructor.
* @param region The region that the player is trying to resell
* @param player The player that is trying to buy this region from the current owner
*/
@ -22,7 +22,7 @@ public class ResellingRegionEvent extends CancellableRegionEvent<BuyRegion> {
}
/**
* Get the player that is trying to buy the region
* Get the player that is trying to buy the region.
* @return The player that is trying to buy the region
*/
public Player getBuyer() {

View File

@ -4,12 +4,12 @@ import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.BuyRegion;
/**
* Broadcasted when a region is about to get sold
* Broadcasted when a region is about to get sold.
*/
public class SellingRegionEvent extends CancellableRegionEvent<BuyRegion> {
/**
* Constructor
* Constructor.
* @param region The region that is about to get sold
*/
public SellingRegionEvent(BuyRegion region) {

View File

@ -4,12 +4,12 @@ import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.RentRegion;
/**
* Broadcasted when a region is about to be unrented
* Broadcasted when a region is about to be unrented.
*/
public class UnrentingRegionEvent extends CancellableRegionEvent<RentRegion> {
/**
* Constructor
* Constructor.
* @param region The region that is about to be unrented
*/
public UnrentingRegionEvent(RentRegion region) {

View File

@ -6,7 +6,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region
* Broadcasted when a friend is being added to a region.
*/
public class AddedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
@ -14,7 +14,7 @@ public class AddedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
private CommandSender by;
/**
* Constructor
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
@ -26,7 +26,7 @@ public class AddedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
}
/**
* Get the OfflinePlayer that is getting added as friend
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
@ -34,7 +34,7 @@ public class AddedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
}
/**
* Get the CommandSender that is adding the friend
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {

View File

@ -6,7 +6,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region
* Broadcasted when a friend is being added to a region.
*/
public class DeletedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
@ -14,7 +14,7 @@ public class DeletedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
private CommandSender by;
/**
* Constructor
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
@ -26,7 +26,7 @@ public class DeletedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
}
/**
* Get the OfflinePlayer that is getting added as friend
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
@ -34,7 +34,7 @@ public class DeletedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
}
/**
* Get the CommandSender that is adding the friend
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {

View File

@ -4,12 +4,12 @@ import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop
* Broadcasted when a region has been added to AreaShop.
*/
public class AddedRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Constructor
* Constructor.
* @param region The region that has been added
*/
public AddedRegionEvent(GeneralRegion region) {

View File

@ -4,12 +4,12 @@ import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.BuyRegion;
/**
* Broadcasted when a region has been bought
* Broadcasted when a region has been bought.
*/
public class BoughtRegionEvent extends NotifyRegionEvent<BuyRegion> {
/**
* Constructor
* Constructor.
* @param region The region that has been bought
*/
public BoughtRegionEvent(BuyRegion region) {

View File

@ -4,12 +4,12 @@ import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been removed from AreaShop
* Broadcasted when a region has been removed from AreaShop.
*/
public class DeletedRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Constructor
* Constructor.
* @param region The region that has been removed
*/
public DeletedRegionEvent(GeneralRegion region) {

View File

@ -4,14 +4,14 @@ import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.RentRegion;
/**
* Broadcasted when a region has been rented
* Broadcasted when a region has been rented.
*/
public class RentedRegionEvent extends NotifyRegionEvent<RentRegion> {
private boolean extended;
/**
* Constructor
* Constructor.
* @param region The region that has been rented
* @param extended true if the region has been extended, false if this is the first time buying the region
*/
@ -22,7 +22,7 @@ public class RentedRegionEvent extends NotifyRegionEvent<RentRegion> {
}
/**
* Check if the region was extended or rented for the first time
* Check if the region was extended or rented for the first time.
* @return true if the region was extended, false when rented for the first time
*/
public boolean hasExtended() {

View File

@ -6,14 +6,14 @@ import me.wiefferink.areashop.regions.BuyRegion;
import java.util.UUID;
/**
* Broadcasted when a region has been resold
* Broadcasted when a region has been resold.
*/
public class ResoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
private UUID from;
/**
* Constructor
* Constructor.
* @param region The region that has been resold
* @param from The player from who the region has been resold to the current owner
*/
@ -23,7 +23,7 @@ public class ResoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
}
/**
* Get the player that the region has been bought from
* Get the player that the region has been bought from.
* @return The UUID of the player that the region has been bought from
*/
public UUID getFromPlayer() {

View File

@ -6,7 +6,7 @@ import me.wiefferink.areashop.regions.BuyRegion;
import java.util.UUID;
/**
* Broadcasted when a region is sold
* Broadcasted when a region is sold.
*/
public class SoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
@ -14,9 +14,9 @@ public class SoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
private double refundedMoney;
/**
* Constructor
* @param region The region that has been sold
* @param oldBuyer The player for which the region has been sold
* Constructor.
* @param region The region that has been sold
* @param oldBuyer The player for which the region has been sold
* @param refundedMoney The amount of money that has been refunded
*/
public SoldRegionEvent(BuyRegion region, UUID oldBuyer, double refundedMoney) {
@ -26,7 +26,7 @@ public class SoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
}
/**
* Get the player that the region is sold for
* Get the player that the region is sold for.
* @return The UUID of the player that the region is sold for
*/
public UUID getOldBuyer() {
@ -34,7 +34,7 @@ public class SoldRegionEvent extends NotifyRegionEvent<BuyRegion> {
}
/**
* Get the amount that is paid back to the player
* Get the amount that is paid back to the player.
* @return The amount of money paid back to the player
*/
public double getRefundedMoney() {

View File

@ -6,7 +6,7 @@ import me.wiefferink.areashop.regions.RentRegion;
import java.util.UUID;
/**
* Broadcasted when a region has been unrented
* Broadcasted when a region has been unrented.
*/
public class UnrentedRegionEvent extends NotifyRegionEvent<RentRegion> {
@ -14,9 +14,9 @@ public class UnrentedRegionEvent extends NotifyRegionEvent<RentRegion> {
private double refundedMoney;
/**
* Constructor
* @param region The region that has been unrented
* @param oldRenter The player that rented the region before it was unrented
* Constructor.
* @param region The region that has been unrented
* @param oldRenter The player that rented the region before it was unrented
* @param refundedMoney The amount of money that has been refunded
*/
public UnrentedRegionEvent(RentRegion region, UUID oldRenter, double refundedMoney) {
@ -26,7 +26,7 @@ public class UnrentedRegionEvent extends NotifyRegionEvent<RentRegion> {
}
/**
* Get the player that the region was unrented for
* Get the player that the region was unrented for.
* @return The UUID of the player that the region was unrented for
*/
public UUID getOldRenter() {
@ -34,7 +34,7 @@ public class UnrentedRegionEvent extends NotifyRegionEvent<RentRegion> {
}
/**
* Get the amount that is paid back to the player
* Get the amount that is paid back to the player.
* @return The amount of money paid back to the player
*/
public double getRefundedMoney() {

View File

@ -10,7 +10,7 @@ import me.wiefferink.areashop.regions.GeneralRegion;
public class UpdateRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Contructor
* Contructor.
* @param region The region that has been updated
*/
public UpdateRegionEvent(GeneralRegion region) {

View File

@ -1,10 +1,21 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.*;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.askandnotify.AddedFriendEvent;
import me.wiefferink.areashop.events.askandnotify.DeletedFriendEvent;
import me.wiefferink.areashop.events.notify.*;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.event.EventHandler;
@ -27,7 +38,7 @@ public class DebugFeature extends RegionFeature {
@EventHandler
public void soldRegion(SoldRegionEvent event) {
AreaShop.debug("SoldRegionEvent: "+Utils.toName(event.getOldBuyer())+" sold "+event.getRegion().getName());
AreaShop.debug("SoldRegionEvent: " + Utils.toName(event.getOldBuyer()) + " sold " + event.getRegion().getName());
}
@EventHandler
@ -37,7 +48,7 @@ public class DebugFeature extends RegionFeature {
@EventHandler
public void resoldRegion(ResoldRegionEvent event) {
AreaShop.debug("ResoldRegionEvent: "+Utils.toName(event.getFromPlayer())+" resold "+event.getRegion().getName()+" to "+event.getRegion().getPlayerName());
AreaShop.debug("ResoldRegionEvent: " + Utils.toName(event.getFromPlayer()) + " resold " + event.getRegion().getName() + " to " + event.getRegion().getPlayerName());
}
@EventHandler
@ -57,7 +68,7 @@ public class DebugFeature extends RegionFeature {
@EventHandler
public void unrentedRegion(UnrentedRegionEvent event) {
AreaShop.debug("UnrentedRegionEvent: "+Utils.toName(event.getOldRenter())+" unrented "+event.getRegion().getName());
AreaShop.debug("UnrentedRegionEvent: " + Utils.toName(event.getOldRenter()) + " unrented " + event.getRegion().getName());
}
@EventHandler
@ -67,21 +78,21 @@ public class DebugFeature extends RegionFeature {
@EventHandler
public void addedRegion(AddedRegionEvent event) {
AreaShop.debug("AddedRegionEvent: "+event.getRegion().getName());
AreaShop.debug("AddedRegionEvent: " + event.getRegion().getName());
}
@EventHandler
public void removedRegion(DeletedRegionEvent event) {
AreaShop.debug("DeletedRegionEvent: "+event.getRegion().getName());
AreaShop.debug("DeletedRegionEvent: " + event.getRegion().getName());
}
@EventHandler
public void addedFriend(AddedFriendEvent event) {
AreaShop.debug("AddedFriendEvent: region "+event.getRegion().getName()+", "+event.getFriend().getName()+" by "+(event.getBy() == null ? "<nobody>" : event.getBy().getName()));
AreaShop.debug("AddedFriendEvent: region " + event.getRegion().getName() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
@EventHandler
public void deleteFriend(DeletedFriendEvent event) {
AreaShop.debug("DeletedFriendEvent: region "+event.getRegion().getName()+", "+event.getFriend().getName()+" by "+(event.getBy() == null ? "<nobody>" : event.getBy().getName()));
AreaShop.debug("DeletedFriendEvent: region " + event.getRegion().getName() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
}

View File

@ -7,7 +7,11 @@ import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class FriendsFeature extends RegionFeature {
@ -16,7 +20,7 @@ public class FriendsFeature extends RegionFeature {
}
/**
* Add a friend to the region
* Add a friend to the region.
* @param player The UUID of the player to add
* @param by The CommandSender that is adding the friend, or null
* @return true if the friend has been added, false if adding a friend was cancelled by another plugin
@ -38,7 +42,7 @@ public class FriendsFeature extends RegionFeature {
}
/**
* Delete a friend from the region
* Delete a friend from the region.
* @param player The UUID of the player to delete
* @param by The CommandSender that is adding the friend, or null
* @return true if the friend has been added, false if adding a friend was cancelled by another plugin
@ -64,7 +68,7 @@ public class FriendsFeature extends RegionFeature {
}
/**
* Get the list of friends added to this region
* Get the list of friends added to this region.
* @return Friends added to this region
*/
public Set<UUID> getFriends() {
@ -81,7 +85,7 @@ public class FriendsFeature extends RegionFeature {
}
/**
* Get the list of friends added to this region
* Get the list of friends added to this region.
* @return Friends added to this region
*/
public Set<String> getFriendNames() {
@ -96,7 +100,7 @@ public class FriendsFeature extends RegionFeature {
}
/**
* Remove all friends that are added to this region
* Remove all friends that are added to this region.
*/
public void clearFriends() {
region.setSetting("general.friends", null);

View File

@ -13,14 +13,14 @@ public abstract class RegionFeature implements Listener {
GeneralRegion region;
/**
* Start listening to events
* Start listening to events.
*/
public void listen() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Destroy the feature and deregister everything
* Destroy the feature and deregister everything.
*/
public void shutdownFeature() {
HandlerList.unregisterAll(this);
@ -28,7 +28,7 @@ public abstract class RegionFeature implements Listener {
}
/**
* Dummy method a RegionFeature implementation can override
* Dummy method a RegionFeature implementation can override.
*/
public void shutdown() {
}

View File

@ -16,7 +16,11 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SignsFeature extends RegionFeature {
@ -28,6 +32,10 @@ public class SignsFeature extends RegionFeature {
}
/**
* Constructor.
* @param region The region to bind to
*/
public SignsFeature(GeneralRegion region) {
this.region = region;
signs = new HashMap<>();
@ -38,7 +46,7 @@ public class SignsFeature extends RegionFeature {
RegionSign sign = new RegionSign(region, signKey);
Location location = sign.getLocation();
if(location == null) {
AreaShop.warn("Sign with key "+signKey+" of region "+region.getName()+" does not have a proper location");
AreaShop.warn("Sign with key " + signKey + " of region " + region.getName() + " does not have a proper location");
continue;
}
signs.put(sign.getStringLocation(), sign);
@ -58,16 +66,16 @@ public class SignsFeature extends RegionFeature {
}
/**
* Convert a location to a string to use as map key
* Convert a location to a string to use as map key.
* @param location The location to get the key for
* @return A string to use in a map for a location
*/
private static String locationToString(Location location) {
return location.getWorld().getName()+";"+location.getBlockX()+";"+location.getBlockY()+";"+location.getBlockZ();
return location.getWorld().getName() + ";" + location.getBlockX() + ";" + location.getBlockY() + ";" + location.getBlockZ();
}
/**
* Get a sign by a location
* Get a sign by a location.
* @param location The location to get the sign for
* @return The RegionSign that is at the location, or null if none
*/
@ -81,31 +89,31 @@ public class SignsFeature extends RegionFeature {
}
/**
* Update all signs connected to this region
* Update all signs connected to this region.
* @return true if all signs are updated correctly, false if one or more updates failed
*/
public boolean update() {
boolean result = true;
for(RegionSign sign : signs.values()) {
result = result&sign.update();
result = result & sign.update();
}
return result;
}
/**
* Check if any of the signs need periodic updating
* Check if any of the signs need periodic updating.
* @return true if one or more of the signs need periodic updating, otherwise false
*/
public boolean needsPeriodicUpdate() {
boolean result = false;
for(RegionSign sign : signs.values()) {
result = result|sign.needsPeriodicUpdate();
result = result | sign.needsPeriodicUpdate();
}
return result;
}
/**
* Get a list with all sign locations
* Get a list with all sign locations.
* @return A List with all sign locations
*/
public List<Location> getSignLocations() {
@ -117,7 +125,7 @@ public class SignsFeature extends RegionFeature {
}
/**
* Add a sign to this region
* Add a sign to this region.
* @param location The location of the sign
* @param signType The type of the sign (WALL_SIGN or SIGN_POST)
* @param facing The orientation of the sign
@ -125,15 +133,15 @@ public class SignsFeature extends RegionFeature {
*/
public void addSign(Location location, Material signType, BlockFace facing, String profile) {
int i = 0;
while(region.getConfig().isSet("general.signs."+i)) {
while(region.getConfig().isSet("general.signs." + i)) {
i++;
}
String signPath = "general.signs."+i+".";
region.setSetting(signPath+"location", Utils.locationToConfig(location));
region.setSetting(signPath+"facing", facing.name());
region.setSetting(signPath+"signType", signType.name());
String signPath = "general.signs." + i + ".";
region.setSetting(signPath + "location", Utils.locationToConfig(location));
region.setSetting(signPath + "facing", facing.name());
region.setSetting(signPath + "signType", signType.name());
if(profile != null && profile.length() != 0) {
region.setSetting(signPath+"profile", profile);
region.setSetting(signPath + "profile", profile);
}
// Add to the map
RegionSign sign = new RegionSign(region, i + "");
@ -142,7 +150,7 @@ public class SignsFeature extends RegionFeature {
}
/**
* Checks if there is a sign from this region at the specified location
* Checks if there is a sign from this region at the specified location.
* @param location Location to check
* @return true if this region has a sign at the location, otherwise false
*/
@ -153,7 +161,7 @@ public class SignsFeature extends RegionFeature {
}
signs = region.getConfig().getConfigurationSection("general.signs").getKeys(false);
for(String sign : signs) {
Location signLocation = Utils.configToLocation(region.getConfig().getConfigurationSection("general.signs."+sign+".location"));
Location signLocation = Utils.configToLocation(region.getConfig().getConfigurationSection("general.signs." + sign + ".location"));
if(signLocation != null
&& signLocation.getWorld().equals(location.getWorld())
&& signLocation.getBlockX() == location.getBlockX()
@ -167,7 +175,7 @@ public class SignsFeature extends RegionFeature {
/**
* Sign that is connected to a region to display information and interact with the region
* Sign that is connected to a region to display information and interact with the region.
*/
public class RegionSign {
@ -180,15 +188,15 @@ public class SignsFeature extends RegionFeature {
}
/**
* Get the location of this sign
* Get the location of this sign.
* @return The location of this sign
*/
public Location getLocation() {
return Utils.configToLocation(region.getConfig().getConfigurationSection("general.signs."+key+".location"));
return Utils.configToLocation(region.getConfig().getConfigurationSection("general.signs." + key + ".location"));
}
/**
* Location string to be used as key in maps
* Location string to be used as key in maps.
* @return Location string
*/
public String getStringLocation() {
@ -196,7 +204,7 @@ public class SignsFeature extends RegionFeature {
}
/**
* Get the region this sign is linked to
* Get the region this sign is linked to.
* @return The region this sign is linked to
*/
public GeneralRegion getRegion() {
@ -204,25 +212,25 @@ public class SignsFeature extends RegionFeature {
}
/**
* Remove this sign from the region
* Remove this sign from the region.
*/
public void remove() {
getLocation().getBlock().setType(Material.AIR);
signs.remove(getStringLocation());
allSigns.remove(getStringLocation());
region.setSetting("general.signs."+key, null);
region.setSetting("general.signs." + key, null);
}
/**
* Get the ConfigurationSection defining the sign layout
* Get the ConfigurationSection defining the sign layout.
* @return The sign layout config
*/
public ConfigurationSection getProfile() {
return region.getConfigurationSectionSetting("general.signProfile", "signProfiles", region.getConfig().get("general.signs."+key+".profile"));
return region.getConfigurationSectionSetting("general.signProfile", "signProfiles", region.getConfig().get("general.signs." + key + ".profile"));
}
/**
* Update this sign
* Update this sign.
* @return true if the update was successful, otherwise false
*/
public boolean update() {
@ -244,7 +252,7 @@ public class SignsFeature extends RegionFeature {
String[] signLines = new String[4];
boolean signEmpty = true;
for(int i = 0; i < 4; i++) {
signLines[i] = stateConfig.getString("line"+(i+1));
signLines[i] = stateConfig.getString("line" + (i + 1));
signEmpty &= (signLines[i] == null || signLines[i].isEmpty());
}
if(signEmpty) {
@ -257,8 +265,8 @@ public class SignsFeature extends RegionFeature {
if(block.getType() != Material.WALL_SIGN && block.getType() != Material.SIGN_POST) {
Material signType;
try {
signType = Material.valueOf(regionConfig.getString("general.signs."+key+".signType"));
} catch(NullPointerException|IllegalArgumentException e) {
signType = Material.valueOf(regionConfig.getString("general.signs." + key + ".signType"));
} catch(NullPointerException | IllegalArgumentException e) {
signType = null;
}
if(signType != Material.WALL_SIGN && signType != Material.SIGN_POST) {
@ -270,8 +278,8 @@ public class SignsFeature extends RegionFeature {
org.bukkit.material.Sign signData = (org.bukkit.material.Sign)signState.getData();
BlockFace signFace;
try {
signFace = BlockFace.valueOf(regionConfig.getString("general.signs."+key+".facing"));
} catch(NullPointerException|IllegalArgumentException e) {
signFace = BlockFace.valueOf(regionConfig.getString("general.signs." + key + ".facing"));
} catch(NullPointerException | IllegalArgumentException e) {
signFace = null;
}
if(signFace != null) {
@ -285,11 +293,11 @@ public class SignsFeature extends RegionFeature {
// Save current rotation and type
org.bukkit.material.Sign signData = (org.bukkit.material.Sign)signState.getData();
if(!regionConfig.isString("general.signs."+key+".signType")) {
region.setSetting("general.signs."+key+".signType", signState.getType().toString());
if(!regionConfig.isString("general.signs." + key + ".signType")) {
region.setSetting("general.signs." + key + ".signType", signState.getType().toString());
}
if(!regionConfig.isString("general.signs."+key+".facing")) {
region.setSetting("general.signs."+key+".facing", signData.getFacing().toString());
if(!regionConfig.isString("general.signs." + key + ".facing")) {
region.setSetting("general.signs." + key + ".facing", signData.getFacing().toString());
}
// Apply replacements and color and then set it on the sign
@ -307,7 +315,7 @@ public class SignsFeature extends RegionFeature {
}
/**
* Check if the sign needs to update periodically
* Check if the sign needs to update periodically.
* @return true if it needs periodic updates, otherwise false
*/
public boolean needsPeriodicUpdate() {
@ -318,8 +326,8 @@ public class SignsFeature extends RegionFeature {
ConfigurationSection stateConfig = signConfig.getConfigurationSection(region.getState().getValue().toLowerCase());
// Check the lines for the timeleft tag
for(int i = 1; i <= 4; i++) {
String line = stateConfig.getString("line"+i);
if(line != null && !line.isEmpty() && line.contains(Message.VARIABLESTART+AreaShop.tagTimeLeft+Message.VARIABLEEND)) {
String line = stateConfig.getString("line" + i);
if(line != null && !line.isEmpty() && line.contains(Message.VARIABLE_START + AreaShop.tagTimeLeft + Message.VARIABLE_END)) {
return true;
}
}
@ -327,7 +335,7 @@ public class SignsFeature extends RegionFeature {
}
/**
* Run commands when a player clicks a sign
* Run commands when a player clicks a sign.
* @param clicker The player that clicked the sign
* @param clickType The type of clicking
* @return true if the commands ran successfully, false if any of them failed
@ -341,15 +349,16 @@ public class SignsFeature extends RegionFeature {
// Run player commands if specified
List<String> playerCommands = new ArrayList<>();
for(String command : stateConfig.getStringList(clickType.getValue()+"Player")) {
playerCommands.add(command.replace(Message.VARIABLESTART+AreaShop.tagClicker+Message.VARIABLEEND, clicker.getName()));
for(String command : stateConfig.getStringList(clickType.getValue() + "Player")) {
// TODO move variable checking code to InteractiveMessenger?
playerCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
region.runCommands(clicker, playerCommands);
// Run console commands if specified
List<String> consoleCommands = new ArrayList<>();
for(String command : stateConfig.getStringList(clickType.getValue()+"Console")) {
consoleCommands.add(command.replace(Message.VARIABLESTART+AreaShop.tagClicker+Message.VARIABLEEND, clicker.getName()));
for(String command : stateConfig.getStringList(clickType.getValue() + "Console")) {
consoleCommands.add(command.replace(Message.VARIABLE_START + AreaShop.tagClicker + Message.VARIABLE_END, clicker.getName()));
}
region.runCommands(Bukkit.getConsoleSender(), consoleCommands);

View File

@ -12,7 +12,11 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TeleportFeature extends RegionFeature {
@ -29,7 +33,7 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Get the teleportlocation set for this region
* Get the teleportlocation set for this region.
* @return The teleport location, or null if not set
*/
public Location getTeleportLocation() {
@ -39,7 +43,7 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Check if the region has a teleportLocation specified
* Check if the region has a teleportLocation specified.
* @return true if the region has a teleportlocation, false otherwise
*/
public boolean hasTeleportLocation() {
@ -47,7 +51,7 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Set the teleport location of this region
* Set the teleport location of this region.
* @param location The location to set as teleport location
*/
public void setTeleport(Location location) {
@ -59,9 +63,9 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Teleport a player to the region or sign
* @param player Player that should be teleported
* @param toSign true to teleport to the first sign of the region, false for teleporting to the region itself
* Teleport a player to the region or sign.
* @param player Player that should be teleported
* @param toSign true to teleport to the first sign of the region, false for teleporting to the region itself
* @param checkRestrictions Set to true if teleport permissions should be checked, false otherwise, also toggles cross-world check
* @return true if the teleport succeeded, otherwise false
*/
@ -77,8 +81,6 @@ public class TeleportFeature extends RegionFeature {
return false;
}
ProtectedRegion wRegion = region.getRegion();
if(checkRestrictions) {
// Check correct world
if(!region.getBooleanSetting("general.teleportCrossWorld") && !player.getWorld().equals(region.getWorld())) {
@ -140,7 +142,8 @@ public class TeleportFeature extends RegionFeature {
// Check locations starting from startLocation and then a cube that increases
// radius around that (until no block in the region is found at all cube sides)
Location safeLocation = startLocation;
boolean blocksInRegion = wRegion.contains(startLocation.getBlockX(), startLocation.getBlockY(), startLocation.getBlockZ());
ProtectedRegion worldguardRegion = region.getRegion();
boolean blocksInRegion = worldguardRegion.contains(startLocation.getBlockX(), startLocation.getBlockY(), startLocation.getBlockZ());
if(!blocksInRegion && insideRegion) {
region.message(player, "teleport-blocked");
return false;
@ -161,13 +164,13 @@ public class TeleportFeature extends RegionFeature {
// North side
continueThisDirection = false;
for(int x = -radius+1; x <= radius && !done && !northDone; x++) {
for(int y = -radius+1; y < radius && !done; y++) {
for(int x = -radius + 1; x <= radius && !done && !northDone; x++) {
for(int y = -radius + 1; y < radius && !done; y++) {
safeLocation = startLocation.clone().add(x, y, -radius);
if(safeLocation.getBlockY() > 256 || safeLocation.getBlockY() < 0) {
continue;
}
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -179,13 +182,13 @@ public class TeleportFeature extends RegionFeature {
// East side
continueThisDirection = false;
for(int z = -radius+1; z <= radius && !done && !eastDone; z++) {
for(int y = -radius+1; y < radius && !done; y++) {
for(int z = -radius + 1; z <= radius && !done && !eastDone; z++) {
for(int y = -radius + 1; y < radius && !done; y++) {
safeLocation = startLocation.clone().add(radius, y, z);
if(safeLocation.getBlockY() > 256 || safeLocation.getBlockY() < 0) {
continue;
}
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -197,13 +200,13 @@ public class TeleportFeature extends RegionFeature {
// South side
continueThisDirection = false;
for(int x = radius-1; x >= -radius && !done && !southDone; x--) {
for(int y = -radius+1; y < radius && !done; y++) {
for(int x = radius - 1; x >= -radius && !done && !southDone; x--) {
for(int y = -radius + 1; y < radius && !done; y++) {
safeLocation = startLocation.clone().add(x, y, radius);
if(safeLocation.getBlockY() > 256 || safeLocation.getBlockY() < 0) {
continue;
}
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -215,13 +218,13 @@ public class TeleportFeature extends RegionFeature {
// West side
continueThisDirection = false;
for(int z = radius-1; z >= -radius && !done && !westDone; z--) {
for(int y = -radius+1; y < radius && !done; y++) {
for(int z = radius - 1; z >= -radius && !done && !westDone; z--) {
for(int y = -radius + 1; y < radius && !done; y++) {
safeLocation = startLocation.clone().add(-radius, y, z);
if(safeLocation.getBlockY() > 256 || safeLocation.getBlockY() < 0) {
continue;
}
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -234,12 +237,12 @@ public class TeleportFeature extends RegionFeature {
// Top side
continueThisDirection = false;
// Middle block of the top
if((startLocation.getBlockY()+radius) > 256) {
if((startLocation.getBlockY() + radius) > 256) {
topDone = true;
}
if(!done && !topDone) {
safeLocation = startLocation.clone().add(0, radius, 0);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -248,9 +251,9 @@ public class TeleportFeature extends RegionFeature {
}
for(int r = 1; r <= radius && !done && !topDone; r++) {
// North
for(int x = -r+1; x <= r && !done; x++) {
for(int x = -r + 1; x <= r && !done; x++) {
safeLocation = startLocation.clone().add(x, radius, -r);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -258,9 +261,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// East
for(int z = -r+1; z <= r && !done; z++) {
for(int z = -r + 1; z <= r && !done; z++) {
safeLocation = startLocation.clone().add(r, radius, z);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -268,9 +271,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// South side
for(int x = r-1; x >= -r && !done; x--) {
for(int x = r - 1; x >= -r && !done; x--) {
safeLocation = startLocation.clone().add(x, radius, r);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -278,9 +281,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// West side
for(int z = r-1; z >= -r && !done; z--) {
for(int z = r - 1; z >= -r && !done; z--) {
safeLocation = startLocation.clone().add(-r, radius, z);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -293,12 +296,12 @@ public class TeleportFeature extends RegionFeature {
// Bottom side
continueThisDirection = false;
// Middle block of the bottom
if(startLocation.getBlockY()-radius < 0) {
if(startLocation.getBlockY() - radius < 0) {
bottomDone = true;
}
if(!done && !bottomDone) {
safeLocation = startLocation.clone().add(0, -radius, 0);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -307,9 +310,9 @@ public class TeleportFeature extends RegionFeature {
}
for(int r = 1; r <= radius && !done && !bottomDone; r++) {
// North
for(int x = -r+1; x <= r && !done; x++) {
for(int x = -r + 1; x <= r && !done; x++) {
safeLocation = startLocation.clone().add(x, -radius, -r);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -317,9 +320,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// East
for(int z = -r+1; z <= r && !done; z++) {
for(int z = -r + 1; z <= r && !done; z++) {
safeLocation = startLocation.clone().add(r, -radius, z);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -327,9 +330,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// South side
for(int x = r-1; x >= -r && !done; x--) {
for(int x = r - 1; x >= -r && !done; x--) {
safeLocation = startLocation.clone().add(x, -radius, r);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -337,9 +340,9 @@ public class TeleportFeature extends RegionFeature {
}
}
// West side
for(int z = r-1; z >= -r && !done; z--) {
for(int z = r - 1; z >= -r && !done; z--) {
safeLocation = startLocation.clone().add(-r, -radius, z);
if(wRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
if(worldguardRegion.contains(safeLocation.getBlockX(), safeLocation.getBlockY(), safeLocation.getBlockZ()) || !insideRegion) {
checked++;
done = isSafe(safeLocation) || checked > maxTries;
blocksInRegion = true;
@ -359,17 +362,17 @@ public class TeleportFeature extends RegionFeature {
region.message(player, "teleport-success");
}
player.teleport(safeLocation);
AreaShop.debug("Found location: "+safeLocation.toString()+" Tries: "+(checked-1));
AreaShop.debug("Found location: " + safeLocation.toString() + " Tries: " + (checked - 1));
return true;
} else {
region.message(player, "teleport-noSafe", checked-1, maxTries);
AreaShop.debug("No location found, checked "+(checked-1)+" spots of max "+maxTries);
region.message(player, "teleport-noSafe", checked - 1, maxTries);
AreaShop.debug("No location found, checked " + (checked - 1) + " spots of max " + maxTries);
return false;
}
}
/**
* Teleport a player to the region or sign when he has permissions for it
* Teleport a player to the region or sign when he has permissions for it.
* @param player Player that should be teleported
* @param toSign true to teleport to the first sign of the region, false for teleporting to the region itself
* @return true if the teleport succeeded, otherwise false
@ -379,7 +382,7 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Teleport a player to the region when he has permissions for it
* Teleport a player to the region when he has permissions for it.
* @param player Player that should be teleported
* @return true if the teleport succeeded, otherwise false
*/
@ -388,7 +391,7 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Checks if a certain location is safe to teleport to
* Checks if a certain location is safe to teleport to.
* @param location The location to check
* @return true if it is safe, otherwise false
*/
@ -434,14 +437,14 @@ public class TeleportFeature extends RegionFeature {
}
/**
* Get the start location of a safe teleport search
* Get the start location of a safe teleport search.
* @param player The player to get it for
* @param toSign true to try teleporting to the first sign, false for teleporting to the region
* @return The start location
*/
private Location getStartLocation(Player player, Value<Boolean> toSign) {
Location startLocation = null;
ProtectedRegion wRegion = region.getRegion();
ProtectedRegion worldguardRegion = region.getRegion();
// Handle teleporting to a sign
List<Location> signs = region.getSignsFeature().getSignLocations();
@ -467,12 +470,12 @@ public class TeleportFeature extends RegionFeature {
// Calculate a default location
if(startLocation == null) {
// Set to block in the middle, y configured in the config
Vector middle = Vector.getMidpoint(wRegion.getMaximumPoint(), wRegion.getMinimumPoint());
Vector middle = Vector.getMidpoint(worldguardRegion.getMaximumPoint(), worldguardRegion.getMinimumPoint());
String configSetting = region.getStringSetting("general.teleportLocationY");
if("bottom".equalsIgnoreCase(configSetting)) {
middle = middle.setY(wRegion.getMinimumPoint().getBlockY());
middle = middle.setY(worldguardRegion.getMinimumPoint().getBlockY());
} else if("top".equalsIgnoreCase(configSetting)) {
middle = middle.setY(wRegion.getMaximumPoint().getBlockY());
middle = middle.setY(worldguardRegion.getMaximumPoint().getBlockY());
} else if("middle".equalsIgnoreCase(configSetting)) {
middle = middle.setY(middle.getBlockY());
} else {
@ -480,15 +483,15 @@ public class TeleportFeature extends RegionFeature {
int vertical = Integer.parseInt(configSetting);
middle = middle.setY(vertical);
} catch(NumberFormatException e) {
AreaShop.warn("Could not parse general.teleportLocationY: '"+configSetting+"'");
AreaShop.warn("Could not parse general.teleportLocationY: '" + configSetting + "'");
}
}
startLocation = new Location(region.getWorld(), middle.getX(), middle.getY(), middle.getZ(), player.getLocation().getYaw(), player.getLocation().getPitch());
}
// Set location in the center of the block
startLocation.setX(startLocation.getBlockX()+0.5);
startLocation.setZ(startLocation.getBlockZ()+0.5);
startLocation.setX(startLocation.getBlockX() + 0.5);
startLocation.setZ(startLocation.getBlockZ() + 0.5);
return startLocation;
}

View File

@ -23,7 +23,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
}
/**
* Set the region flags/options to the values of a ConfigurationSection
* Set the region flags/options to the values of a ConfigurationSection.
* @param region The region to update the flags for
* @return true if the flags have been set correctly, otherwise false
*/
@ -50,10 +50,11 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
return result;
}
/**
* Set the region flags/options to the values of a ConfigurationSection
* Set the region flags/options to the values of a ConfigurationSection.
* @param region The region to update the flags for
* @param flags The flags to apply
* @param flags The flags to apply
* @return true if the flags have been set correctly, otherwise false
*/
private boolean updateRegionFlags(GeneralRegion region, ConfigurationSection flags) {
@ -63,8 +64,8 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
WorldGuardPlugin worldGuard = plugin.getWorldGuard();
// Get the region
ProtectedRegion wRegion = region.getRegion();
if(wRegion == null) {
ProtectedRegion worldguardRegion = region.getRegion();
if(worldguardRegion == null) {
AreaShop.debug("Region '" + region.getName() + "' does not exist, setting flags failed");
return false;
}
@ -76,18 +77,18 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
value = translateBukkitToWorldGuardColors(value);
}
if(flagName.equalsIgnoreCase("members")) {
plugin.getWorldGuardHandler().setMembers(wRegion, value);
plugin.getWorldGuardHandler().setMembers(worldguardRegion, value);
//AreaShop.debug(" Flag " + flagName + " set: " + members.toUserFriendlyString());
} else if(flagName.equalsIgnoreCase("owners")) {
plugin.getWorldGuardHandler().setOwners(wRegion, value);
plugin.getWorldGuardHandler().setOwners(worldguardRegion, value);
//AreaShop.debug(" Flag " + flagName + " set: " + owners.toUserFriendlyString());
} else if(flagName.equalsIgnoreCase("priority")) {
try {
int priority = Integer.parseInt(value);
wRegion.setPriority(priority);
worldguardRegion.setPriority(priority);
//AreaShop.debug(" Flag " + flagName + " set: " + value);
} catch(NumberFormatException e) {
AreaShop.warn("The value of flag "+flagName+" is not a number");
AreaShop.warn("The value of flag " + flagName + " is not a number");
result = false;
}
} else if(flagName.equalsIgnoreCase("parent")) {
@ -97,7 +98,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
ProtectedRegion parentRegion = worldGuard.getRegionManager(region.getWorld()).getRegion(value);
if(parentRegion != null) {
try {
wRegion.setParent(parentRegion);
worldguardRegion.setParent(parentRegion);
//AreaShop.debug(" Flag " + flagName + " set: " + value);
} catch(ProtectedRegion.CircularInheritanceException e) {
AreaShop.warn("The parent set in the config is not correct (circular inheritance)");
@ -112,14 +113,14 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
Flag<?> foundFlag = plugin.getWorldGuardHandler().fuzzyMatchFlag(flagName);
if(foundFlag == null) {
AreaShop.warn("Found wrong flag in flagProfiles section: "+flagName+", check if that is the correct WorldGuard flag");
AreaShop.warn("Found wrong flag in flagProfiles section: " + flagName + ", check if that is the correct WorldGuard flag");
continue;
}
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
if(value == null || value.isEmpty()) {
wRegion.setFlag(foundFlag, null);
worldguardRegion.setFlag(foundFlag, null);
if(groupFlag != null) {
wRegion.setFlag(groupFlag, null);
worldguardRegion.setFlag(groupFlag, null);
}
//AreaShop.debug(" Flag " + flagName + " reset (+ possible group of flag)");
} else {
@ -132,7 +133,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
try {
groupValue = plugin.getWorldGuardHandler().parseFlagGroupInput(groupFlag, part.substring(2));
} catch(InvalidFlagFormat e) {
AreaShop.warn("Found wrong group value for flag "+flagName);
AreaShop.warn("Found wrong group value for flag " + flagName);
}
}
} else {
@ -146,18 +147,18 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
}
if(flagSetting != null) {
try {
setFlag(wRegion, foundFlag, flagSetting);
setFlag(worldguardRegion, foundFlag, flagSetting);
//AreaShop.debug(" Flag " + flagName + " set: " + flagSetting);
} catch(InvalidFlagFormat e) {
AreaShop.warn("Found wrong value for flag "+flagName);
AreaShop.warn("Found wrong value for flag " + flagName);
}
}
if(groupValue != null) {
if(groupValue == groupFlag.getDefault()) {
wRegion.setFlag(groupFlag, null);
worldguardRegion.setFlag(groupFlag, null);
//AreaShop.debug(" Group of flag " + flagName + " set to default: " + groupValue);
} else {
wRegion.setFlag(groupFlag, groupValue);
worldguardRegion.setFlag(groupFlag, groupValue);
//AreaShop.debug(" Group of flag " + flagName + " set: " + groupValue);
}
}
@ -170,11 +171,11 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
}
/**
* Set a WorldGuard region flag
* Set a WorldGuard region flag.
* @param region The WorldGuard region to set
* @param flag The flag to set
* @param value The value to set the flag to
* @param <V> They type of flag to set
* @param <V> They type of flag to set
* @throws InvalidFlagFormat When the value of the flag is wrong
*/
private <V> void setFlag(ProtectedRegion region, Flag<V> flag, String value) throws InvalidFlagFormat {
@ -182,7 +183,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
}
/**
* Translate the color codes you put in greeting/farewell messages to the weird color codes of WorldGuard
* Translate the color codes you put in greeting/farewell messages to the weird color codes of WorldGuard.
* @param message The message where the color codes should be translated (this message has bukkit color codes)
* @return The string with the WorldGuard color codes
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -19,21 +19,21 @@ import java.util.ArrayList;
import java.util.List;
/**
* Notify region expiry and track activity time
* Notify region expiry and track activity time.
*/
public final class PlayerLoginLogoutListener implements Listener {
private AreaShop plugin;
/**
* Constructor
* Constructor.
* @param plugin The AreaShop plugin
*/
public PlayerLoginLogoutListener(AreaShop plugin) {
this.plugin = plugin;
}
/**
* Called when a sign is changed
* Called when a sign is changed.
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
@ -44,16 +44,16 @@ public final class PlayerLoginLogoutListener implements Listener {
final Player player = event.getPlayer();
// Notify admins for plugin updates
if(plugin.updateAvailable() && player.hasPermission("areashop.notifyupdate")) {
AreaShop.getInstance().message(player, "update-playerNotify", AreaShop.getInstance().getDescription().getVersion(), AreaShop.getInstance().getUpdater().getLatestName());
AreaShop.getInstance().message(player, "update-playerNotify", AreaShop.getInstance().getDescription().getVersion(), AreaShop.getInstance().getUpdater().getLatestName());
}
// Schedule task to check for notifications, prevents a lag spike at login
new BukkitRunnable() {
new BukkitRunnable() {
@Override
public void run() {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return;
}
}
if(!player.isOnline()) {
this.cancel();
return;
@ -68,18 +68,18 @@ public final class PlayerLoginLogoutListener implements Listener {
long warningTime = Utils.durationStringToLong(warningSetting);
if(region.getTimeLeft() < warningTime) {
// Send the warning message later to let it appear after general MOTD messages
AreaShop.getInstance().message(player, "rent-expireWarning", region);
}
AreaShop.getInstance().message(player, "rent-expireWarning", region);
}
}
}
this.cancel();
}
}.runTaskTimer(plugin, 25, 25);
}.runTaskTimer(plugin, 25, 25);
// Check if the player has regions that use an old name of him and update them
final List<GeneralRegion> regions = new ArrayList<>(plugin.getFileManager().getRegions());
new BukkitRunnable() {
private int current = 0;
@Override
public void run() {
// Delay until all regions are loaded
@ -87,17 +87,17 @@ public final class PlayerLoginLogoutListener implements Listener {
return;
}
// Check all regions
for(int i=0; i<plugin.getConfig().getInt("nameupdate.regionsPerTick"); i++) {
for(int i = 0; i < plugin.getConfig().getInt("nameupdate.regionsPerTick"); i++) {
if(current < regions.size()) {
GeneralRegion region = regions.get(current);
if(region.isOwner(player)) {
if (region instanceof BuyRegion) {
if(!player.getName().equals(region.getStringSetting("buy.buyerName"))) {
if(region instanceof BuyRegion) {
if(!player.getName().equals(region.getStringSetting("buy.buyerName"))) {
region.setSetting("buy.buyerName", player.getName());
region.update();
}
} else if (region instanceof RentRegion) {
if(!player.getName().equals(region.getStringSetting("rent.renterName"))) {
} else if(region instanceof RentRegion) {
if(!player.getName().equals(region.getStringSetting("rent.renterName"))) {
region.setSetting("rent.renterName", player.getName());
region.update();
}
@ -112,20 +112,20 @@ public final class PlayerLoginLogoutListener implements Listener {
}
}.runTaskTimer(plugin, 22, 1); // Wait a bit before starting to prevent a lot of stress on the server when a player joins (a lot of plugins already do stuff then)
}
// Active time updates
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogout(PlayerQuitEvent event) {
updateLastActive(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerKick(PlayerKickEvent event) {
updateLastActive(event.getPlayer());
}
/**
* Update the last active time for all regions the player is owner off
* Update the last active time for all regions the player is owner off.
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {

View File

@ -12,22 +12,22 @@ import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
/**
* Checks for placement of signs for this plugin
* Checks for placement of signs for this plugin.
*/
public final class SignBreakListener implements Listener {
private AreaShop plugin;
/**
* Constructor
* Constructor.
* @param plugin The AreaShop plugin
*/
public SignBreakListener(AreaShop plugin) {
this.plugin = plugin;
}
/**
* Called when a block is broken
* Called when a block is broken.
* @param event The event
*/
@EventHandler(priority = EventPriority.HIGH)
@ -53,29 +53,29 @@ public final class SignBreakListener implements Listener {
}
}
}
/**
* Called when the physics of a block change
* Called when the physics of a block change.
* @param event The event
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onIndirectSignBreak(BlockPhysicsEvent event){
Block block = event.getBlock();
if(event.isCancelled()) {
return;
}
if(block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN){
Sign sign = (Sign)block.getState();
Block attachedTo = block.getRelative(((org.bukkit.material.Sign)sign.getData()).getAttachedFace());
if(attachedTo.getType() == Material.AIR){
public void onIndirectSignBreak(BlockPhysicsEvent event) {
Block block = event.getBlock();
if(event.isCancelled()) {
return;
}
if(block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) {
Sign sign = (Sign)block.getState();
Block attachedTo = block.getRelative(((org.bukkit.material.Sign)sign.getData()).getAttachedFace());
if(attachedTo.getType() == Material.AIR) {
// Check if the rent sign is really the same as a saved rent
SignsFeature.RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if(regionSign != null) {
event.setCancelled(true); // Cancel the sign breaking, will create a floating sign but at least it is not disconnected/gone
}
}
}
}
}
}
}
}

View File

@ -21,21 +21,21 @@ import java.util.List;
import java.util.Set;
/**
* Checks for placement of signs
* Checks for placement of signs.
*/
public final class SignChangeListener implements Listener {
private AreaShop plugin;
/**
* Constructor
* Constructor.
* @param plugin The AreaShop plugin
*/
public SignChangeListener(AreaShop plugin) {
this.plugin = plugin;
}
/**
* Called when a sign is changed
* Called when a sign is changed.
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
@ -48,22 +48,22 @@ public final class SignChangeListener implements Listener {
plugin.message(player, "general-notReady");
return;
}
// Check if the sign is meant for this plugin
if(event.getLine(0).contains(plugin.getConfig().getString("signTags.rent"))) {
if(!player.hasPermission("areashop.createrent") && !player.hasPermission("areashop.createrent.member") && !player.hasPermission("areashop.createrent.owner")) {
plugin.message(player, "setup-noPermissionRent");
plugin.message(player, "setup-noPermissionRent");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
String fourthLine = event.getLine(3);
// Get the regionManager for accessing regions
RegionManager regionManager = plugin.getWorldGuard().getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if(secondLine == null || secondLine.length() == 0) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
@ -93,8 +93,8 @@ public final class SignChangeListener implements Listener {
secondLine = candidate.getId();
}
}
}
}
boolean priceSet = fourthLine != null && fourthLine.length() != 0;
boolean durationSet = thirdLine != null && thirdLine.length() != 0;
// check if all the lines are correct
@ -123,19 +123,19 @@ public final class SignChangeListener implements Listener {
// Check the fourth line
try {
price = Double.parseDouble(fourthLine);
} catch (NumberFormatException e) {
} catch(NumberFormatException e) {
plugin.message(player, "setup-wrongPrice");
return;
}
}
// Add rent to the FileManager
final RentRegion rent = new RentRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = plugin.getWorldGuardHandler().containsMember(rent.getRegion(), player.getUniqueId());
boolean isOwner = plugin.getWorldGuardHandler().containsOwner(rent.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createrent")
&& ((player.hasPermission("areashop.createrent.owner") && isOwner)
|| (player.hasPermission("areashop.createrent.member") && isMember)));
|| (player.hasPermission("areashop.createrent.member") && isMember)));
if(landlord) {
rent.setLandlord(player.getUniqueId(), player.getName());
@ -151,7 +151,7 @@ public final class SignChangeListener implements Listener {
// Run commands
rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
plugin.getFileManager().addRent(rent);
rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-rentSuccess", rent);
@ -165,10 +165,10 @@ public final class SignChangeListener implements Listener {
// Run commands
rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
}
} else if (event.getLine(0).contains(plugin.getConfig().getString("signTags.buy"))) {
} else if(event.getLine(0).contains(plugin.getConfig().getString("signTags.buy"))) {
// Check for permission
if(!player.hasPermission("areashop.createbuy") && !player.hasPermission("areashop.createbuy.member") && !player.hasPermission("areashop.createbuy.owner")) {
plugin.message(player, "setup-noPermissionBuy");
plugin.message(player, "setup-noPermissionBuy");
return;
}
@ -234,19 +234,19 @@ public final class SignChangeListener implements Listener {
// Check the fourth line
try {
price = Double.parseDouble(thirdLine);
} catch (NumberFormatException e) {
} catch(NumberFormatException e) {
plugin.message(player, "setup-wrongPrice");
return;
}
}
// Add buy to the FileManager
final BuyRegion buy = new BuyRegion(secondLine, event.getPlayer().getWorld());
boolean isMember = plugin.getWorldGuardHandler().containsMember(buy.getRegion(), player.getUniqueId());
boolean isOwner = plugin.getWorldGuardHandler().containsOwner(buy.getRegion(), player.getUniqueId());
boolean landlord = (!player.hasPermission("areashop.createbuy")
&& ((player.hasPermission("areashop.createbuy.owner") && isOwner)
|| (player.hasPermission("areashop.createbuy.member") && isMember)));
|| (player.hasPermission("areashop.createbuy.member") && isMember)));
if(landlord) {
buy.setLandlord(player.getUniqueId(), player.getName());
@ -258,7 +258,7 @@ public final class SignChangeListener implements Listener {
buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null);
// Run commands
buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
plugin.getFileManager().addBuy(buy);
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-buySuccess", buy);
@ -276,10 +276,10 @@ public final class SignChangeListener implements Listener {
} else if(event.getLine(0).contains(plugin.getConfig().getString("signTags.add"))) {
// Check for permission
if(!player.hasPermission("areashop.addsign")) {
plugin.message(player, "addsign-noPermission");
plugin.message(player, "addsign-noPermission");
return;
}
// Get the other lines
String secondLine = event.getLine(1);
String thirdLine = event.getLine(2);
@ -291,10 +291,10 @@ public final class SignChangeListener implements Listener {
if(region == null) {
plugin.message(player, "cmd-noRegion", secondLine);
return;
}
}
} else {
// Get region by sign position
List<GeneralRegion> regions = Utils.getASRegionsInSelection(new CuboidSelection(event.getBlock().getWorld(), event.getBlock().getLocation(), event.getBlock().getLocation()));
List<GeneralRegion> regions = Utils.getRegionsInSelection(new CuboidSelection(event.getBlock().getWorld(), event.getBlock().getLocation(), event.getBlock().getLocation()));
if(regions.isEmpty()) {
plugin.message(player, "addsign-noRegions");
return;

View File

@ -14,9 +14,9 @@ import org.bukkit.event.player.PlayerInteractEvent;
public class SignClickListener implements Listener {
private AreaShop plugin;
/**
* Constructor
* Constructor.
* @param plugin The AreaShop plugin
*/
public SignClickListener(AreaShop plugin) {
@ -24,7 +24,7 @@ public class SignClickListener implements Listener {
}
/**
* Called when a player interacts
* Called when a player interacts.
* @param event The event
*/
@EventHandler(priority = EventPriority.HIGH)
@ -34,7 +34,7 @@ public class SignClickListener implements Listener {
}
Block block = event.getClickedBlock();
// Check for clicking a sign and rightclicking
if((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)
if((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)
&& (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
// Check if the rent sign is really the same as a saved rent
SignsFeature.RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());

View File

@ -1,6 +1,38 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.commands.*;
import me.wiefferink.areashop.commands.AddCommand;
import me.wiefferink.areashop.commands.AddfriendCommand;
import me.wiefferink.areashop.commands.AddsignCommand;
import me.wiefferink.areashop.commands.BuyCommand;
import me.wiefferink.areashop.commands.CommandAreaShop;
import me.wiefferink.areashop.commands.DelCommand;
import me.wiefferink.areashop.commands.DelfriendCommand;
import me.wiefferink.areashop.commands.DelsignCommand;
import me.wiefferink.areashop.commands.FindCommand;
import me.wiefferink.areashop.commands.GroupaddCommand;
import me.wiefferink.areashop.commands.GroupdelCommand;
import me.wiefferink.areashop.commands.GroupinfoCommand;
import me.wiefferink.areashop.commands.GrouplistCommand;
import me.wiefferink.areashop.commands.HelpCommand;
import me.wiefferink.areashop.commands.InfoCommand;
import me.wiefferink.areashop.commands.LinksignsCommand;
import me.wiefferink.areashop.commands.MeCommand;
import me.wiefferink.areashop.commands.MessageCommand;
import me.wiefferink.areashop.commands.ReloadCommand;
import me.wiefferink.areashop.commands.RentCommand;
import me.wiefferink.areashop.commands.ResellCommand;
import me.wiefferink.areashop.commands.SchematiceventCommand;
import me.wiefferink.areashop.commands.SellCommand;
import me.wiefferink.areashop.commands.SetdurationCommand;
import me.wiefferink.areashop.commands.SetlandlordCommand;
import me.wiefferink.areashop.commands.SetownerCommand;
import me.wiefferink.areashop.commands.SetpriceCommand;
import me.wiefferink.areashop.commands.SetrestoreCommand;
import me.wiefferink.areashop.commands.SetteleportCommand;
import me.wiefferink.areashop.commands.StackCommand;
import me.wiefferink.areashop.commands.StopresellCommand;
import me.wiefferink.areashop.commands.TeleportCommand;
import me.wiefferink.areashop.commands.UnrentCommand;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@ -13,9 +45,9 @@ import java.util.TreeSet;
public class CommandManager extends Manager implements CommandExecutor, TabCompleter {
private ArrayList<CommandAreaShop> commands;
/**
* Constructor
* Constructor.
*/
public CommandManager() {
commands = new ArrayList<>();
@ -53,20 +85,20 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
commands.add(new MessageCommand());
// Register commands in bukkit
plugin.getCommand("AreaShop").setExecutor(this);
plugin.getCommand("AreaShop").setExecutor(this);
plugin.getCommand("AreaShop").setTabCompleter(this);
}
}
/**
* Get the list with AreaShop commands
* Get the list with AreaShop commands.
* @return The list with AreaShop commands
*/
public ArrayList<CommandAreaShop> getCommands() {
return commands;
}
/**
* Shows the help page for the CommandSender
* Shows the help page for the CommandSender.
* @param target The CommandSender to show the help to
*/
public void showHelp(CommandSender target) {
@ -89,7 +121,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
plugin.messageNoPrefix(target, message);
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if(!plugin.isReady()) {
@ -102,8 +134,8 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
args[1] = args[2];
}
// Execute command
boolean executed = false;
for(int i=0; i<commands.size() && !executed; i++) {
boolean executed = false;
for(int i = 0; i < commands.size() && !executed; i++) {
if(commands.get(i).canExecute(command, args)) {
commands.get(i).execute(sender, args);
executed = true;
@ -129,12 +161,12 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
return result;
}
int toCompleteNumber = args.length;
String toCompletePrefix = args[args.length-1].toLowerCase();
String toCompletePrefix = args[args.length - 1].toLowerCase();
//AreaShop.debug("toCompleteNumber=" + toCompleteNumber + ", toCompletePrefix=" + toCompletePrefix + ", length=" + toCompletePrefix.length());
if(toCompleteNumber == 1) {
for(CommandAreaShop c : commands) {
String begin = c.getCommandStart();
result.add(begin.substring(begin.indexOf(' ') +1));
result.add(begin.substring(begin.indexOf(' ') + 1));
}
} else {
String[] start = new String[args.length];
@ -153,7 +185,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
if(suggestion.toLowerCase().startsWith(toCompletePrefix)) {
set.add(suggestion);
}
}
}
result.clear();
result.addAll(set);
}

View File

@ -1,12 +1,21 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.features.*;
import me.wiefferink.areashop.features.DebugFeature;
import me.wiefferink.areashop.features.FriendsFeature;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.features.SignsFeature;
import me.wiefferink.areashop.features.TeleportFeature;
import me.wiefferink.areashop.features.WorldGuardRegionFlagsFeature;
import me.wiefferink.areashop.regions.GeneralRegion;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class FeatureManager extends Manager {
@ -22,6 +31,9 @@ public class FeatureManager extends Manager {
private Set<RegionFeature> globalFeatures;
private Map<Class<? extends RegionFeature>, Constructor<? extends RegionFeature>> regionFeatureConstructors;
/**
* Constructor.
*/
public FeatureManager() {
// Instantiate and register global features (one per type, for event handling)
globalFeatures = new HashSet<>();
@ -32,7 +44,7 @@ public class FeatureManager extends Manager {
RegionFeature feature = constructor.newInstance();
feature.listen();
globalFeatures.add(feature);
} catch(InstantiationException|IllegalAccessException|InvocationTargetException|IllegalArgumentException e) {
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
AreaShop.error("Failed to instantiate global feature:", clazz);
}
} catch(NoSuchMethodException e) {
@ -45,7 +57,7 @@ public class FeatureManager extends Manager {
for(Class<? extends RegionFeature> clazz : featureClasses) {
try {
regionFeatureConstructors.put(clazz, clazz.getConstructor(GeneralRegion.class));
} catch(NoSuchMethodException|IllegalArgumentException e) {
} catch(NoSuchMethodException | IllegalArgumentException e) {
// The feature does not have a region specific part
}
}
@ -59,15 +71,15 @@ public class FeatureManager extends Manager {
}
/**
* Instanciate a feature for a certain region
* @param region The region to create a feature for
* Instanciate a feature for a certain region.
* @param region The region to create a feature for
* @param featureClazz The class of the feature to create
* @return The feature class
*/
public RegionFeature getRegionFeature(GeneralRegion region, Class<? extends RegionFeature> featureClazz) {
try {
return regionFeatureConstructors.get(featureClazz).newInstance(region);
} catch(InstantiationException|InvocationTargetException|IllegalAccessException|IllegalArgumentException e) {
} catch(InstantiationException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
AreaShop.error("Failed to instanciate feature", featureClazz, "for region", region);
}
return null;

View File

@ -7,7 +7,7 @@ public abstract class Manager {
AreaShop plugin = AreaShop.getInstance();
/**
* Called at shutdown of the plugin
* Called at shutdown of the plugin.
*/
public void shutdown() {
// To override by extending classes

View File

@ -19,7 +19,12 @@ import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.material.Sign;
import org.bukkit.util.BlockIterator;
import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class SignLinkerManager extends Manager implements Listener {
private Map<UUID, SignLinker> signLinkers;
@ -36,10 +41,10 @@ public class SignLinkerManager extends Manager implements Listener {
exitSignLinkMode(Bukkit.getPlayer(uuid));
}
}
/**
* Let a player enter sign linking mode
* @param player The player that has to enter sign linking mode
* Let a player enter sign linking mode.
* @param player The player that has to enter sign linking mode
* @param profile The profile to use for the signs (null for default)
*/
public void enterSignLinkMode(Player player, String profile) {
@ -51,9 +56,9 @@ public class SignLinkerManager extends Manager implements Listener {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
}
/**
* Let a player exit sign linking mode
* Let a player exit sign linking mode.
* @param player The player that has to exit sign linking mode
*/
public void exitSignLinkMode(Player player) {
@ -64,9 +69,9 @@ public class SignLinkerManager extends Manager implements Listener {
}
plugin.message(player, "linksigns-stopped");
}
/**
* Check if the player is in sign linking mode
* Check if the player is in sign linking mode.
* @param player The player to check
* @return true if the player is in sign linking mode, otherwise false
*/
@ -75,7 +80,7 @@ public class SignLinkerManager extends Manager implements Listener {
}
/**
* On player interactions
* On player interactions.
* @param event The PlayerInteractEvent
*/
@EventHandler(priority = EventPriority.HIGH)
@ -89,7 +94,7 @@ public class SignLinkerManager extends Manager implements Listener {
BlockIterator blockIterator = new BlockIterator(player, 100);
while(blockIterator.hasNext()) {
Block next = blockIterator.next();
List<GeneralRegion> regions = Utils.getASRegionsByLocation(next.getLocation());
List<GeneralRegion> regions = Utils.getRegions(next.getLocation());
if(regions.size() == 1) {
linker.setRegion(regions.get(0));
return;
@ -101,7 +106,7 @@ public class SignLinkerManager extends Manager implements Listener {
plugin.message(player, "linksigns-multipleRegions", Utils.createCommaSeparatedList(names));
plugin.message(player, "linksigns-multipleRegionsAdvice");
return;
}
}
}
// No regions found within the maximum range
plugin.message(player, "linksigns-noRegions");
@ -129,37 +134,37 @@ public class SignLinkerManager extends Manager implements Listener {
}
}
}
/**
* Handle disconnection players
* Handle disconnection players.
* @param event The PlayerQuitEvent
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLeave(PlayerQuitEvent event) {
exitSignLinkMode(event.getPlayer());
}
/**
* Class to keep track of the signlinking data
* Class to keep track of the signlinking data.
*/
private class SignLinker {
private boolean hasSign = false;
private boolean hasRegion = false;
public Player linker = null;
public String profile = null;
public GeneralRegion region = null;
public Location location = null;
public Material type = null;
public BlockFace facing = null;
public SignLinker(Player linker, String profile) {
this.linker = linker;
this.profile = profile;
}
public void setRegion(GeneralRegion region) {
this.region = region;
hasRegion = true;
@ -168,7 +173,7 @@ public class SignLinkerManager extends Manager implements Listener {
}
finish();
}
public void setSign(Location location, Material type, BlockFace facing) {
this.location = location;
this.type = type;
@ -190,21 +195,21 @@ public class SignLinkerManager extends Manager implements Listener {
}
region.update();
reset();
plugin.message(linker, "linksigns-next");
}
}
public void reset() {
hasSign = false;
hasRegion = false;
}
public boolean isComplete() {
return hasSign && hasRegion;
}
}
}

View File

@ -28,12 +28,12 @@ public class BuyRegion extends GeneralRegion {
public BuyRegion(String name, World world) {
super(name, world);
}
@Override
public RegionType getType() {
return RegionType.BUY;
}
@Override
public RegionState getState() {
if(isSold() && isInResellingMode()) {
@ -44,14 +44,14 @@ public class BuyRegion extends GeneralRegion {
return RegionState.FORSALE;
}
}
@Override
public boolean isAvailable() {
return !isSold();
}
/**
* Get the UUID of the owner of this region
* Get the UUID of the owner of this region.
* @return The UUID of the owner of this region
*/
public UUID getBuyer() {
@ -65,22 +65,23 @@ public class BuyRegion extends GeneralRegion {
}
return null;
}
/**
* Check if a player is the buyer of this region
* Check if a player is the buyer of this region.
* @param player Player to check
* @return true if this player owns this region, otherwise false
*/
public boolean isBuyer(Player player) {
return player != null && isBuyer(player.getUniqueId());
}
public boolean isBuyer(UUID player) {
UUID buyer = getBuyer();
return !(buyer == null || player == null) && buyer.equals(player);
}
/**
* Set the buyer of this region
* Set the buyer of this region.
* @param buyer The UUID of the player that should be set as buyer
*/
public void setBuyer(UUID buyer) {
@ -92,9 +93,9 @@ public class BuyRegion extends GeneralRegion {
setSetting("buy.buyerName", Utils.toName(buyer));
}
}
/**
* Get the name of the player that owns this region
* Get the name of the player that owns this region.
* @return The name of the player that owns this region, if unavailable by UUID it will return the old cached name, if that is unavailable it will return &lt;UNKNOWN&gt;
*/
public String getPlayerName() {
@ -107,105 +108,105 @@ public class BuyRegion extends GeneralRegion {
}
return result;
}
/**
* Check if the region is sold
* Check if the region is sold.
* @return true if the region is sold, otherwise false
*/
public boolean isSold() {
return getBuyer() != null;
}
/**
* Check if the region is being resold
* Check if the region is being resold.
* @return true if the region is available for reselling, otherwise false
*/
public boolean isInResellingMode() {
return config.getBoolean("buy.resellMode");
}
/**
* Get the price of the region
* Get the price of the region.
* @return The price of the region
*/
public double getPrice() {
return Math.max(0, Utils.evaluateToDouble(getStringSetting("buy.price"), this));
}
/**
* Get the resell price of this region
* Get the resell price of this region.
* @return The resell price if isInResellingMode(), otherwise 0.0
*/
public double getResellPrice() {
return Math.max(0, config.getDouble("buy.resellPrice"));
}
/**
* Get the formatted string of the price (includes prefix and suffix)
* Get the formatted string of the price (includes prefix and suffix).
* @return The formatted string of the price
*/
public String getFormattedPrice() {
return Utils.formatCurrency(getPrice());
}
/**
* Get the formatted string of the resellprice (includes prefix and suffix)
* Get the formatted string of the resellprice (includes prefix and suffix).
* @return The formatted string of the resellprice
*/
public String getFormattedResellPrice() {
return Utils.formatCurrency(getResellPrice());
}
/**
* Change the price of the region
* Change the price of the region.
* @param price The price to set this region to
*/
public void setPrice(double price) {
setSetting("buy.price", price);
}
/**
* Remove the price so that the price will be taken from a group or the default.yml file
*/
public void removePrice() {
setSetting("buy.price", null);
}
/**
* Set the region into resell mode with the given price
* Set the region into resell mode with the given price.
* @param price The price this region should be put up for sale
*/
public void enableReselling(double price) {
setSetting("buy.resellMode", true);
setSetting("buy.resellPrice", price);
}
/**
* Stop this region from being in resell mode
* Stop this region from being in resell mode.
*/
public void disableReselling() {
setSetting("buy.resellMode", null);
setSetting("buy.resellPrice", null);
}
/**
* Get the moneyBack percentage
* Get the moneyBack percentage.
* @return The % of money the player will get back when selling
*/
public double getMoneyBackPercentage() {
return Utils.evaluateToDouble(getStringSetting("buy.moneyBack"), this);
}
/**
* Get the amount of money that should be paid to the player when selling the region
* Get the amount of money that should be paid to the player when selling the region.
* @return The amount of money the player should get back
*/
public double getMoneyBackAmount() {
return getPrice() * (getMoneyBackPercentage() / 100.0);
}
/**
* Get the formatted string of the amount of the moneyBack amount
* Get the formatted string of the amount of the moneyBack amount.
* @return String with currency symbols and proper fractional part
*/
public String getFormattedMoneyBackAmount() {
@ -232,7 +233,7 @@ public class BuyRegion extends GeneralRegion {
case AreaShop.tagRawMoneyBackAmount:
return getMoneyBackAmount();
case AreaShop.tagMoneyBackPercentage:
return getMoneyBackPercentage()%1.0 == 0.0 ? (int)getMoneyBackPercentage() : getMoneyBackPercentage();
return getMoneyBackPercentage() % 1.0 == 0.0 ? (int)getMoneyBackPercentage() : getMoneyBackPercentage();
case AreaShop.tagMaxInactiveTime:
return this.getFormattedInactiveTimeUntilSell();
@ -240,25 +241,25 @@ public class BuyRegion extends GeneralRegion {
return super.provideReplacement(variable);
}
}
/**
* Minutes until automatic unrent when player is offline
* Minutes until automatic unrent when player is offline.
* @return The number of milliseconds until the region is unrented while player is offline
*/
public long getInactiveTimeUntilSell() {
return Utils.getDurationFromMinutesOrStringInput(getStringSetting("buy.inactiveTimeUntilSell"));
}
/**
* Get a human readable string indicating how long the player can be offline until automatic unrent
* Get a human readable string indicating how long the player can be offline until automatic unrent.
* @return String indicating the inactive time until unrent
*/
public String getFormattedInactiveTimeUntilSell() {
return Utils.millisToHumanFormat(getInactiveTimeUntilSell());
}
/**
* Buy a region
* Buy a region.
* @param player The player that wants to buy the region
* @return true if it succeeded and false if not
*/
@ -292,15 +293,15 @@ public class BuyRegion extends GeneralRegion {
if(!isSold() || (isInResellingMode() && !isBuyer(player))) {
boolean isResell = isInResellingMode();
// Check if the players needs to be in the world or region for buying
if(restrictedToRegion() && (!player.getWorld().getName().equals(getWorldName())
if(restrictedToRegion() && (!player.getWorld().getName().equals(getWorldName())
|| !getRegion().contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()))) {
message(player, "buy-restrictedToRegion");
return false;
}
}
if(restrictedToWorld() && !player.getWorld().getName().equals(getWorldName())) {
message(player, "buy-restrictedToWorld", player.getWorld().getName());
return false;
}
}
// Check region limits
LimitResult limitResult = this.limitsAllow(RegionType.BUY, player);
AreaShop.debug("LimitResult: " + limitResult.toString());
@ -344,11 +345,11 @@ public class BuyRegion extends GeneralRegion {
if(oldOwnerPlayer != null && oldOwnerPlayer.getName() != null) {
r = plugin.getEconomy().depositPlayer(oldOwnerPlayer, getWorldName(), getResellPrice());
oldOwnerName = oldOwnerPlayer.getName();
} else if (oldOwnerName != null) {
} else if(oldOwnerName != null) {
r = plugin.getEconomy().depositPlayer(oldOwnerName, getWorldName(), getResellPrice());
}
if(r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '"+oldOwnerName+"' "+getFormattedPrice()+" for his resell of region "+getName()+" to "+player.getName());
AreaShop.warn("Something went wrong with paying '" + oldOwnerName + "' " + getFormattedPrice() + " for his resell of region " + getName() + " to " + player.getName());
}
// Resell is done, disable that now
disableReselling();
@ -400,7 +401,7 @@ public class BuyRegion extends GeneralRegion {
r = plugin.getEconomy().depositPlayer(landlordName, getWorldName(), getPrice());
}
if(r != null && !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '"+landlordName+"' "+getFormattedPrice()+" for his sell of region "+getName()+" to "+player.getName());
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + getFormattedPrice() + " for his sell of region " + getName() + " to " + player.getName());
}
}
@ -420,7 +421,7 @@ public class BuyRegion extends GeneralRegion {
message(player, "buy-succes");
// Run commands
this.runEventCommands(RegionEvent.BOUGHT, false);
}
}
return true;
} else {
// Player has not enough money
@ -436,17 +437,17 @@ public class BuyRegion extends GeneralRegion {
} else {
message(player, "buy-someoneElse");
}
}
}
} else {
message(player, "buy-noPermission");
}
return false;
}
/**
* Sell a buyed region, get part of the money back
* Sell a buyed region, get part of the money back.
* @param giveMoneyBack true if the player should be given money back, otherwise false
* @param executor CommandSender to receive a message when the sell fails, or null
* @param executor CommandSender to receive a message when the sell fails, or null
* @return true if the region has been sold, otherwise false
*/
@SuppressWarnings("deprecation")
@ -477,10 +478,10 @@ public class BuyRegion extends GeneralRegion {
// Run commands
this.runEventCommands(RegionEvent.SOLD, true);
disableReselling();
// Give part of the buying price back
double moneyBack = getMoneyBackAmount();
double moneyBack = getMoneyBackAmount();
if(moneyBack > 0 && giveMoneyBack) {
boolean noPayBack = false;
OfflinePlayer landlordPlayer = null;
@ -498,8 +499,8 @@ public class BuyRegion extends GeneralRegion {
if(r == null || !r.transactionSuccess()) {
noPayBack = true;
}
}
}
// Give back the money
OfflinePlayer player = Bukkit.getOfflinePlayer(getBuyer());
if(player != null && !noPayBack) {
@ -515,8 +516,8 @@ public class BuyRegion extends GeneralRegion {
error = true;
}
if(error || response == null || !response.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying back money to "+getPlayerName()+" while selling region "+getName());
}
AreaShop.warn("Something went wrong with paying back money to " + getPlayerName() + " while selling region " + getName());
}
}
}
@ -552,8 +553,8 @@ public class BuyRegion extends GeneralRegion {
long lastPlayed = getLastActiveTime();
//AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
if(Calendar.getInstance().getTimeInMillis() > (lastPlayed + inactiveSetting)) {
AreaShop.info("Region "+getName()+" unrented because of inactivity for player "+getPlayerName());
AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
AreaShop.info("Region " + getName() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis() - player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
return this.sell(true, null);
}
return false;

View File

@ -30,7 +30,14 @@ import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public abstract class GeneralRegion implements GeneralRegionInterface, Comparable<GeneralRegion>, ReplacementProvider {
static final AreaShop plugin = AreaShop.getInstance();
@ -42,22 +49,23 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
private Map<Class<? extends RegionFeature>, RegionFeature> features;
// Enum for region types
public enum RegionType {
public enum RegionType {
RENT("rent"),
BUY("buy");
private final String value;
RegionType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
// Enum for schematic event types
public enum RegionEvent {
public enum RegionEvent {
CREATED("created"),
DELETED("deleted"),
RENTED("rented"),
@ -66,12 +74,13 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
BOUGHT("bought"),
SOLD("sold"),
RESELL("resell");
private final String value;
RegionEvent(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@ -90,6 +99,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
RegionState(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@ -101,36 +111,38 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
LEFTCLICK("leftClick"),
SHIFTRIGHTCLICK("shiftRightClick"),
SHIFTLEFTCLICK("shiftLeftClick");
private final String value;
ClickType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
// Enum for limit types
public enum LimitType {
public enum LimitType {
RENTS("rents"),
BUYS("buys"),
TOTAL("total"),
EXTEND("extend");
private final String value;
LimitType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* Constructor, used to restore regions from disk at startup
* Constructor, used to restore regions from disk at startup.
* @param config The configuration of the region
*/
public GeneralRegion(YamlConfiguration config) {
@ -139,8 +151,8 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Constructor, used for adding new regions
* @param name Name of the WorldGuard region that this region is attached to
* Constructor, used for adding new regions.
* @param name Name of the WorldGuard region that this region is attached to
* @param world The world of the WorldGuard region
*/
public GeneralRegion(String name, World world) {
@ -152,14 +164,14 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Shared setup of all constructors
* Shared setup of all constructors.
*/
public void setup() {
features = new HashMap<>();
}
/**
* Deregister everything
* Deregister everything.
*/
public void destroy() {
for(RegionFeature feature : features.values()) {
@ -168,7 +180,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get a feature of this region
* Get a feature of this region.
* @param clazz The class of the feature to get
* @return The feature (either just instanciated or cached)
*/
@ -182,7 +194,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the friends feature to query and manipulate friends of this region
* Get the friends feature to query and manipulate friends of this region.
* @return The FriendsFeature of this region
*/
public FriendsFeature getFriendsFeature() {
@ -190,7 +202,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the signs feature to manipulate and update signs
* Get the signs feature to manipulate and update signs.
* @return The SignsFeature of this region
*/
public SignsFeature getSignsFeature() {
@ -198,22 +210,23 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the teleport feature to teleport players to the region and signs
* Get the teleport feature to teleport players to the region and signs.
* @return The TeleportFeature
*/
public TeleportFeature getTeleportFeature() {
return (TeleportFeature)getFeature(TeleportFeature.class);
}
// ABSTRACT
/**
* Get the region type of the region
* @return The RegionType of this region
*/
public abstract RegionType getType();
/**
* Get the region availability
* Get the region type of the region.
* @return The RegionType of this region
*/
public abstract RegionType getType();
/**
* Get the region availability.
* @return true/false if region cant be rented or sell
*/
public abstract boolean isAvailable();
@ -221,7 +234,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
// Sorting by name
/**
* Compare this region to another region by name
* Compare this region to another region by name.
* @param o The region to compare to
* @return 0 if the names are the same, below zero if this region is earlier in the alphabet, otherwise above zero
*/
@ -229,19 +242,19 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
public int compareTo(@Nonnull GeneralRegion o) {
return getName().compareTo(o.getName());
}
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object region) {
return region instanceof GeneralRegion && ((GeneralRegion)region).getName().equals(getName());
}
/**
* Get the config file that is used to store the region information
* Get the config file that is used to store the region information.
* @return The config file that stores the region information
*/
public YamlConfiguration getConfig() {
@ -257,7 +270,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Broadcast the given event and update the region status
* Broadcast the given event and update the region status.
* @param event The update event that should be broadcasted
*/
public void notifyAndUpdate(NotifyRegionEvent event) {
@ -266,44 +279,46 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the state of a region
* Get the state of a region.
* @return The RegionState of the region
*/
public abstract RegionState getState();
// GETTERS
/**
* Check if the region has been deleted
* Check if the region has been deleted.
* @return true if the region has been deleted, otherwise false
*/
public boolean isDeleted() {
return deleted;
}
/**
* Indicate that this region has been deleted
* Indicate that this region has been deleted.
*/
public void setDeleted() {
deleted = true;
}
/**
* Get the name of the region
* Get the name of the region.
* @return The region name
*/
public String getName() {
return config.getString("general.name");
}
/**
* Get the lowercase region name
* Get the lowercase region name.
* @return The region name in lowercase
*/
public String getLowerCaseName() {
return getName().toLowerCase();
}
/**
* Check if restoring is enabled
* Check if restoring is enabled.
* @return true if restoring is enabled, otherwise false
*/
public boolean isRestoreEnabled() {
@ -311,7 +326,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the time that the player was last active
* Get the time that the player was last active.
* @return Current time if he is online, last online time if offline, -1 if the region has no owner
*/
public long getLastActiveTime() {
@ -326,75 +341,76 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
return savedTime;
}
/**
* Set the last active time of the player to the current time
* Set the last active time of the player to the current time.
*/
public void updateLastActiveTime() {
if(getOwner() != null) {
setSetting("general.lastActive", Calendar.getInstance().getTimeInMillis());
}
}
public void removeLastActiveTime() {
setSetting("general.lastActive", null);
}
/**
* Get the World of the region
* Get the World of the region.
* @return The World where the region is located
*/
public World getWorld() {
return Bukkit.getWorld(getWorldName());
}
/**
* Get the name of the world where the region is located
* Get the name of the world where the region is located.
* @return The name of the world of the region
*/
public String getWorldName() {
return getStringSetting("general.world");
}
/**
* Get the FileManager from the plugin
* Get the FileManager from the plugin.
* @return The FileManager (responsible for saving/loading regions and getting them)
*/
public FileManager getFileManager() {
return plugin.getFileManager();
}
/**
* Check if the players is owner of this region
* Check if the players is owner of this region.
* @param player Player to check ownership for
* @return true if the player currently rents or buys this region
*/
public boolean isOwner(OfflinePlayer player) {
return isOwner(player.getUniqueId());
}
/**
* Check if the players is owner of this region
* Check if the players is owner of this region.
* @param player Player to check ownership for
* @return true if the player currently rents or buys this region
*/
public boolean isOwner(UUID player) {
return (this instanceof RentRegion && ((RentRegion) this).isRenter(player)) || (this instanceof BuyRegion && ((BuyRegion) this).isBuyer(player));
}
return (this instanceof RentRegion && ((RentRegion)this).isRenter(player)) || (this instanceof BuyRegion && ((BuyRegion)this).isBuyer(player));
}
/**
* Get the player that is currently the owner of this region (either bought or rented it)
* Get the player that is currently the owner of this region (either bought or rented it).
* @return The UUID of the owner of this region
*/
public UUID getOwner() {
if (this instanceof RentRegion) {
return ((RentRegion)this).getRenter();
if(this instanceof RentRegion) {
return ((RentRegion)this).getRenter();
} else {
return ((BuyRegion)this).getBuyer();
}
}
/**
* Get the landlord of this region (the player that receives any revenue from this region)
* Get the landlord of this region (the player that receives any revenue from this region).
* @return The UUID of the landlord of this region
*/
public UUID getLandlord() {
@ -415,9 +431,9 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
return null;
}
/**
* Get the name of the landlord
* Get the name of the landlord.
* @return The name of the landlord, if unavailable by UUID it will return the old cached name, if that is unavailable it will return &lt;UNKNOWN&gt;
*/
public String getLandlordName() {
@ -430,11 +446,11 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
return result;
}
/**
* Set the landlord of this region (the player that receives all revenue of this region)
* Set the landlord of this region (the player that receives all revenue of this region).
* @param landlord The UUID of the player that should be set as landlord
* @param name The backup name of the player (for in case that the UUID cannot be resolved to a playername)
* @param name The backup name of the player (for in case that the UUID cannot be resolved to a playername)
*/
public void setLandlord(UUID landlord, String name) {
if(landlord != null) {
@ -446,71 +462,73 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
setSetting("general.landlordName", properName);
}
/**
* Remove the landlord from this region
* Remove the landlord from this region.
*/
public void removelandlord() {
setSetting("general.landlord", null);
setSetting("general.landlordName", null);
}
/**
* Check if the specified player is the landlord of this region
* Check if the specified player is the landlord of this region.
* @param landlord The UUID of the players to check for landlord
* @return true if the player is the landlord, otherwise false
*/
public boolean isLandlord(UUID landlord) {
return landlord !=null && getLandlord() != null && getLandlord().equals(landlord);
return landlord != null && getLandlord() != null && getLandlord().equals(landlord);
}
/**
* Get the WorldGuard region associated with this AreaShop region
* Get the WorldGuard region associated with this AreaShop region.
* @return The ProtectedRegion of WorldGuard or null if the region does not exist anymore
*/
public ProtectedRegion getRegion() {
if(getWorld() == null
|| plugin.getWorldGuard() == null
if(getWorld() == null
|| plugin.getWorldGuard() == null
|| plugin.getWorldGuard().getRegionManager(getWorld()) == null
|| plugin.getWorldGuard().getRegionManager(getWorld()).getRegion(getName()) == null) {
return null;
}
return plugin.getWorldGuard().getRegionManager(getWorld()).getRegion(getName());
}
/**
* Get the width of the region (x-axis)
* Get the width of the region (x-axis).
* @return The width of the region (x-axis)
*/
public int getWidth() {
if(getRegion() == null) {
return 0;
}
return getRegion().getMaximumPoint().getBlockX() - getRegion().getMinimumPoint().getBlockX() +1;
return getRegion().getMaximumPoint().getBlockX() - getRegion().getMinimumPoint().getBlockX() + 1;
}
/**
* Get the depth of the region (z-axis)
* Get the depth of the region (z-axis).
* @return The depth of the region (z-axis)
*/
public int getDepth() {
if(getRegion() == null) {
return 0;
}
return getRegion().getMaximumPoint().getBlockZ() - getRegion().getMinimumPoint().getBlockZ() +1;
return getRegion().getMaximumPoint().getBlockZ() - getRegion().getMinimumPoint().getBlockZ() + 1;
}
/**
* Get the height of the region (y-axis)
* Get the height of the region (y-axis).
* @return The height of the region (y-axis)
*/
public int getHeight() {
if(getRegion() == null) {
return 0;
}
return getRegion().getMaximumPoint().getBlockY() - getRegion().getMinimumPoint().getBlockY() +1;
return getRegion().getMaximumPoint().getBlockY() - getRegion().getMinimumPoint().getBlockY() + 1;
}
/**
* Get the groups that this region is added to
* Get the groups that this region is added to.
* @return A Set with all groups of this region
*/
public Set<RegionGroup> getGroups() {
@ -519,12 +537,12 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
if(group.isMember(this)) {
result.add(group);
}
}
}
return result;
}
/**
* Get a list of names from groups this region is in
* Get a list of names from groups this region is in.
* @return A list of groups this region is part of
*/
public List<String> getGroupNames() {
@ -619,30 +637,30 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Check if for renting this region you should be inside of it
* Check if for renting this region you should be inside of it.
* @return true if you need to be inside, otherwise false
*/
public boolean restrictedToRegion() {
return getBooleanSetting("general.restrictedToRegion");
}
/**
* Check if for renting you need to be in the correct world
* Check if for renting you need to be in the correct world.
* @return true if you need to be in the same world as the region, otherwise false
*/
public boolean restrictedToWorld() {
return getBooleanSetting("general.restrictedToWorld") || restrictedToRegion();
}
/**
* Check now if the player has been inactive for too long, unrent/sell will happen when true
* Check now if the player has been inactive for too long, unrent/sell will happen when true.
* @return true if the region has been unrented/sold, otherwise false
*/
public abstract boolean checkInactive();
/**
* Method to send a message to a CommandSender, using chatprefix if it is a player
* Automatically includes the region in the message, enabling the use of all variables
* Method to send a message to a CommandSender, using chatprefix if it is a player.
* Automatically includes the region in the message, enabling the use of all variables.
* @param target The CommandSender you wan't to send the message to (e.g. a player)
* @param key The key to get the translation
* @param prefix Specify if the message should have a prefix
@ -662,33 +680,33 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
public void message(Object target, String key, Object... params) {
configurableMessage(target, key, true, params);
}
/**
* Check if a sign needs periodic updating
* Check if a sign needs periodic updating.
* @return true if the signs of this region need periodic updating, otherwise false
*/
public boolean needsPeriodicUpdate() {
return !(isDeleted() || !(this instanceof RentRegion)) && getSignsFeature().needsPeriodicUpdate();
}
return !(isDeleted() || !(this instanceof RentRegion)) && getSignsFeature().needsPeriodicUpdate();
}
/**
* Change the restore setting
* Change the restore setting.
* @param restore true, false or general
*/
public void setRestoreSetting(Boolean restore) {
setSetting("general.enableRestore", restore);
}
/**
* Change the restore profile
* Change the restore profile.
* @param profile default or the name of the profile as set in the config
*/
public void setSchematicProfile(String profile) {
setSetting("general.schematicProfile", profile);
}
/**
* Save all blocks in a region for restoring later
* Save all blocks in a region for restoring later.
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been saved properly, otherwise false
*/
@ -701,23 +719,23 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
// The path to save the schematic
File saveFile = new File(plugin.getFileManager().getSchematicFolder() + File.separator + fileName + AreaShop.schematicExtension);
// Create parent directories
File parent = saveFile.getParentFile();
if (parent != null && !parent.exists()) {
if (!parent.mkdirs()) {
AreaShop.warn("Did not save region "+getName()+", schematic directory could not be created: "+saveFile.getAbsolutePath());
// Create parent directories
File parent = saveFile.getParentFile();
if(parent != null && !parent.exists()) {
if(!parent.mkdirs()) {
AreaShop.warn("Did not save region " + getName() + ", schematic directory could not be created: " + saveFile.getAbsolutePath());
return false;
}
}
}
}
boolean result = plugin.getWorldEditHandler().saveRegionBlocks(saveFile, this);
if(result) {
AreaShop.debug("Saved schematic for region " + getName());
}
return true;
}
/**
* Restore all blocks in a region for restoring later
* Restore all blocks in a region for restoring later.
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been restored properly, otherwise false
*/
@ -729,7 +747,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
// The path to save the schematic
File restoreFile = new File(plugin.getFileManager().getSchematicFolder() + File.separator + fileName + AreaShop.schematicExtension);
if(!restoreFile.exists() || !restoreFile.isFile()) {
AreaShop.info("Did not restore region "+getName()+", schematic file does not exist: "+restoreFile.getAbsolutePath());
AreaShop.info("Did not restore region " + getName() + ", schematic file does not exist: " + restoreFile.getAbsolutePath());
return false;
}
boolean result = plugin.getWorldEditHandler().restoreRegionBlocks(restoreFile, this);
@ -746,9 +764,9 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
return result;
}
/**
* Reset all flags of the region
* Reset all flags of the region.
*/
public void resetRegionFlags() {
ProtectedRegion region = getRegion();
@ -757,24 +775,24 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
region.setFlag(DefaultFlag.FAREWELL_MESSAGE, null);
}
}
/**
* Indicate this region needs to be saved, saving will happen by a repeating task
* Indicate this region needs to be saved, saving will happen by a repeating task.
*/
public void saveRequired() {
saveRequired = true;
}
/**
* Check if a save is required
* Check if a save is required.
* @return true if a save is required because some data changed, otherwise false
*/
public boolean isSaveRequired() {
return saveRequired && !isDeleted();
}
/**
* Save this region to disk now, using this method could slow down the plugin, normally saveRequired() should be used
* Save this region to disk now, using this method could slow down the plugin, normally saveRequired() should be used.
* @return true if the region is saved successfully, otherwise false
*/
public boolean saveNow() {
@ -786,7 +804,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
try {
config.save(file);
return true;
} catch (IOException e) {
} catch(IOException e) {
return false;
}
}
@ -806,7 +824,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
if(config.isSet(path)) {
if(config.isString(path)) {
return config.getString(path).equalsIgnoreCase("true");
}
}
return config.getBoolean(path);
}
boolean result = false;
@ -1090,26 +1108,26 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
} else if(result instanceof ConfigurationSection) {
return (ConfigurationSection)result;
} else {
return plugin.getConfig().getConfigurationSection(translateProfileName+"."+result.toString());
return plugin.getConfig().getConfigurationSection(translateProfileName + "." + result.toString());
}
}
/**
* Set a setting in the file of the region itself
* @param path The path to set
* Set a setting in the file of the region itself.
* @param path The path to set
* @param value The value to set it to, null to remove the setting
*/
public void setSetting(String path, Object value) {
config.set(path, value);
this.saveRequired();
}
// LIMIT FUNCTIONS
/**
* Check if the player can buy/rent this region, detailed info in the result object
* @param type The type of region to check
* Check if the player can buy/rent this region, detailed info in the result object.
* @param type The type of region to check
* @param player The player to check it for
* @return LimitResult containing if it is allowed, why and limiting factor
*/
@ -1118,8 +1136,8 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Check if the player can buy/rent this region, detailed info in the result object
* @param type The type of region to check
* Check if the player can buy/rent this region, detailed info in the result object.
* @param type The type of region to check
* @param player The player to check it for
* @param extend Check for extending of rental regions
* @return LimitResult containing if it is allowed, why and limiting factor
@ -1143,15 +1161,15 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
while(!groups.isEmpty()) {
String group = groups.get(0);
if(player.hasPermission("areashop.limits." + group) && this.matchesLimitGroup(group)) {
String pathPrefix = "limitGroups."+group+".";
if(!plugin.getConfig().isInt(pathPrefix+"total")) {
AreaShop.warn("Limit group "+group+" in the config.yml file does not correctly specify the number of total regions (should be specified as total: <number>)");
String pathPrefix = "limitGroups." + group + ".";
if(!plugin.getConfig().isInt(pathPrefix + "total")) {
AreaShop.warn("Limit group " + group + " in the config.yml file does not correctly specify the number of total regions (should be specified as total: <number>)");
}
if(!plugin.getConfig().isInt(pathPrefix+typePath)) {
AreaShop.warn("Limit group "+group+" in the config.yml file does not correctly specify the number of "+typePath+" regions (should be specified as "+typePath+": <number>)");
if(!plugin.getConfig().isInt(pathPrefix + typePath)) {
AreaShop.warn("Limit group " + group + " in the config.yml file does not correctly specify the number of " + typePath + " regions (should be specified as " + typePath + ": <number>)");
}
int totalLimit = plugin.getConfig().getInt("limitGroups." + group + ".total");
int typeLimit = plugin.getConfig().getInt("limitGroups." + group + "."+typePath);
int typeLimit = plugin.getConfig().getInt("limitGroups." + group + "." + typePath);
//AreaShop.debug("typeLimitOther="+typeLimit+", typePath="+typePath);
int totalCurrent = hasRegionsInLimitGroup(player, group, plugin.getFileManager().getRegions(), exclude);
int typeCurrent;
@ -1176,9 +1194,9 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
if(limitGroupsOfSameCategory(group, checkGroup)) {
groups.remove(checkGroup);
int totalLimitOther = plugin.getConfig().getInt("limitGroups." + checkGroup + ".total");
int typeLimitOther = plugin.getConfig().getInt("limitGroups." + checkGroup + "."+typePath);
int typeLimitOther = plugin.getConfig().getInt("limitGroups." + checkGroup + "." + typePath);
if(totalLimitOther > totalLimit) {
totalLimit = totalLimitOther;
totalLimit = totalLimitOther;
totalHighestGroup = checkGroup;
} else if(totalLimitOther == -1) {
totalLimit = Integer.MAX_VALUE;
@ -1206,19 +1224,19 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
} else {
limitType = LimitType.BUYS;
}
return new LimitResult(false, limitType, typeLimit, typeCurrent, typeHighestGroup);
return new LimitResult(false, limitType, typeLimit, typeCurrent, typeHighestGroup);
}
if(totalCurrent >= totalLimit) {
return new LimitResult(false, LimitType.TOTAL, totalLimit, totalCurrent, totalHighestGroup);
}
return new LimitResult(false, LimitType.TOTAL, totalLimit, totalCurrent, totalHighestGroup);
}
}
groups.remove(group);
}
}
return new LimitResult(true, null, 0, 0, null);
}
/**
* Class to store the result of a limits check
* Class to store the result of a limits check.
*/
public class LimitResult {
private boolean actionAllowed;
@ -1226,6 +1244,15 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
private int maximum;
private int current;
private String limitingGroup;
/**
* Constructor.
* @param actionAllowed has the action been allowed?
* @param limitingFactor The LimitType that has prevented the action (if actionAllowed is false)
* @param maximum The maximum number of regions allowed (if actionAllowed is false)
* @param current The current number of regions the player has (if actionAllowed is false)
* @param limitingGroup The group that is enforcing this limit (if actionAllowed is false)
*/
public LimitResult(boolean actionAllowed, LimitType limitingFactor, int maximum, int current, String limitingGroup) {
this.actionAllowed = actionAllowed;
this.limitingFactor = limitingFactor;
@ -1235,7 +1262,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Check if the action is allowed
* Check if the action is allowed.
* @return true if the actions is allowed, otherwise false
*/
public boolean actionAllowed() {
@ -1243,7 +1270,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the type of the factor that is limiting the action, assuming actionAllowed() is false
* Get the type of the factor that is limiting the action, assuming actionAllowed() is false.
* @return The type of the limiting factor
*/
public LimitType getLimitingFactor() {
@ -1251,7 +1278,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the maximum number of the group that is the limiting factor, assuming actionAllowed() is false
* Get the maximum number of the group that is the limiting factor, assuming actionAllowed() is false.
* @return The maximum
*/
public int getMaximum() {
@ -1259,7 +1286,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the current number of regions in the group that is the limiting factor, assuming actionAllowed() is false
* Get the current number of regions in the group that is the limiting factor, assuming actionAllowed() is false.
* @return The current number of regions the player has
*/
public int getCurrent() {
@ -1267,22 +1294,22 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
/**
* Get the name of the group that is limiting the action, assuming actionAllowed() is false
* Get the name of the group that is limiting the action, assuming actionAllowed() is false.
* @return The name of the group
*/
public String getLimitingGroup() {
return limitingGroup;
}
@Override
public String toString() {
return "actionAllowed=" + actionAllowed + ", limitingFactor=" + limitingFactor + ", maximum=" + maximum + ", current=" + current + ", limitingGroup=" + limitingGroup;
}
}
/**
* Checks if two limitGroups are of the same category (same groups and worlds lists)
* @param firstGroup The first group
* Checks if two limitGroups are of the same category (same groups and worlds lists).
* @param firstGroup The first group
* @param secondGroup The second group
* @return true if the groups and worlds lists are the same, otherwise false
*/
@ -1296,13 +1323,13 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
List<String> secondWorlds = plugin.getConfig().getStringList("limitGroups." + secondGroup + ".worlds");
return !(!firstWorlds.containsAll(secondWorlds) || !secondWorlds.containsAll(firstWorlds));
}
/**
* Get the amount of regions a player has matching a certain limits group (config.yml -- limitGroups)
* @param player The player to check the amount for
* @param player The player to check the amount for
* @param limitGroup The group to check
* @param regions All the regions a player has bought or rented
* @param exclude Exclude this region from the count
* @param regions All the regions a player has bought or rented
* @param exclude Exclude this region from the count
* @return The number of regions that the player has bought or rented matching the limit group (worlds and groups filters)
*/
public int hasRegionsInLimitGroup(Player player, String limitGroup, List<? extends GeneralRegion> regions, GeneralRegion exclude) {
@ -1314,9 +1341,9 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
return result;
}
/**
* Check if this region matches the filters of a limit group
* Check if this region matches the filters of a limit group.
* @param group The group to check
* @return true if the region applies to the limit group, otherwise false
*/
@ -1331,20 +1358,20 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
for(RegionGroup checkGroup : plugin.getFileManager().getGroups()) {
inGroups = inGroups || (groups.contains(checkGroup.getName()) && checkGroup.isMember(this));
}
return inGroups;
return inGroups;
}
}
return false;
}
/**
* Checks an event and handles saving to and restoring from schematic for it
* Checks an event and handles saving to and restoring from schematic for it.
* @param type The type of event
*/
public void handleSchematicEvent(RegionEvent type) {
// Check the individual>group>default setting
if(!isRestoreEnabled()) {
AreaShop.debug("Schematic operations for "+getName()+" not enabled, skipped");
AreaShop.debug("Schematic operations for " + getName() + " not enabled, skipped");
return;
}
// Get the safe and restore names
@ -1353,8 +1380,8 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
return;
}
String save = profileSection.getString(type.getValue()+".save");
String restore = profileSection.getString(type.getValue()+".restore");
String save = profileSection.getString(type.getValue() + ".save");
String restore = profileSection.getString(type.getValue() + ".restore");
// Save the region if needed
if(save != null && save.length() != 0) {
save = Message.fromString(save).replacements(this).getSingle();
@ -1366,19 +1393,19 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
restoreRegionBlocks(restore);
}
}
// COMMAND EXECUTING
/**
* Run commands as the CommandsSender, replacing all tags with the relevant values
* @param sender The sender that should perform the command
* Run commands as the CommandsSender, replacing all tags with the relevant values.
* @param sender The sender that should perform the command
* @param commands A list of the commands to run (without slash and with tags)
*/
public void runCommands(CommandSender sender, List<String> commands) {
if(commands == null || commands.isEmpty()) {
return;
}
for(String command : commands) {
if(command == null || command.length() == 0) {
continue;
@ -1401,22 +1428,22 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
if(!result) {
printed = true;
if(error != null) {
AreaShop.warn("Command execution failed, command="+command+", error="+error+", stacktrace:");
AreaShop.warn("Command execution failed, command=" + command + ", error=" + error + ", stacktrace:");
AreaShop.warn(stacktrace);
AreaShop.warn("--- End of stacktrace ---");
} else {
AreaShop.warn("Command execution failed, command="+command);
AreaShop.warn("Command execution failed, command=" + command);
}
}
if(!printed) {
AreaShop.debug("Command run, executor="+sender.getName()+", command=" + command);
AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command);
}
}
}
/**
* Run command for a certain event
* @param event The event
* Run command for a certain event.
* @param event The event
* @param before The 'before' or 'after' commands
*/
public void runEventCommands(RegionEvent event, boolean before) {
@ -1424,7 +1451,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
if(eventCommandProfileSection == null) {
return;
}
List<String> commands = eventCommandProfileSection.getStringList(event.getValue()+"."+(before ? "before" : "after"));
List<String> commands = eventCommandProfileSection.getStringList(event.getValue() + "." + (before ? "before" : "after"));
if(commands == null || commands.isEmpty()) {
return;
}

View File

@ -12,11 +12,11 @@ public class RegionGroup {
private AreaShop plugin;
private String name;
/**
* Constructor, used when creating new groups or restoring them from groups.yml at server boot
* @param plugin The AreaShop plugin
* @param name Name of the group, has to be unique
* @param name Name of the group, has to be unique
*/
public RegionGroup(AreaShop plugin, String name) {
this.plugin = plugin;
@ -45,9 +45,9 @@ public class RegionGroup {
plugin.getFileManager().removeGroup(this);
}
}
/**
* Adds a member to a group
* Adds a member to a group.
* @param region The region to add to the group (GeneralRegion or a subclass of it)
* @return true if the region was not already added, otherwise false
*/
@ -62,9 +62,9 @@ public class RegionGroup {
return true;
}
}
/**
* Remove a member from the group
* Remove a member from the group.
* @param region The region to remove
* @return true if the region was in the group before, otherwise false
*/
@ -82,9 +82,9 @@ public class RegionGroup {
}
return result;
}
/**
* Get all members of the group
* Get all members of the group.
* @return A list with the names of all members of the group
*/
public List<String> getMembers() {
@ -93,9 +93,9 @@ public class RegionGroup {
}
return getSettings().getStringList("regions");
}
/**
* Get all members of the group as GeneralRegions
* Get all members of the group as GeneralRegions.
* @return A Set with all group members
*/
public Set<GeneralRegion> getMemberRegions() {
@ -105,50 +105,51 @@ public class RegionGroup {
}
return result;
}
/**
* Get the name of the group
* Get the name of the group.
* @return The name of the group
*/
public String getName() {
return name;
}
}
/**
* Get the lowercase name of the group (used for getting the config etc)
* Get the lowercase name of the group (used for getting the config etc).
* @return The name of the group in lowercase
*/
public String getLowerCaseName() {
return getName().toLowerCase();
}
/**
* Check if a region is member of the group
* Check if a region is member of the group.
* @param region Region to check
* @return true if the region is in the group, otherwise false
*/
public boolean isMember(GeneralRegion region) {
return getMembers().contains(region.getName());
}
/**
* Get the priority of the group (higher overwrites)
* Get the priority of the group (higher overwrites).
* @return The priority of the group
*/
public int getPriority() {
return getSettings().getInt("priority");
}
/**
* Get the configurationsection with the settings of this group
* Get the configurationsection with the settings of this group.
* @return The ConfigurationSection with the settings of the group
*/
public ConfigurationSection getSettings() {
return plugin.getFileManager().getGroupSettings(name);
}
/**
* Set a setting of this group
* @param path The path to set
* Set a setting of this group.
* @param path The path to set
* @param setting The value to set
*/
public void setSetting(String path, Object setting) {
@ -156,14 +157,14 @@ public class RegionGroup {
}
/**
* Indicates this file needs to be saved, will actually get saved later by a task
* Indicates this file needs to be saved, will actually get saved later by a task.
*/
public void saveRequired() {
plugin.getFileManager().saveGroupsIsRequired();
}
/**
* Save the groups to disk now, normally saveRequired() is preferred because of performance
* Save the groups to disk now, normally saveRequired() is preferred because of performance.
*/
public void saveNow() {
plugin.getFileManager().saveGroupsNow();

View File

@ -25,29 +25,29 @@ import static me.wiefferink.areashop.tools.Utils.millisToHumanFormat;
public class RentRegion extends GeneralRegion {
private long warningsDoneUntil = Calendar.getInstance().getTimeInMillis();
/**
* Constructor
* Constructor.
* @param config All settings of this region
*/
public RentRegion(YamlConfiguration config) {
super(config);
}
/**
* Create a new RentRegion
* @param name The name of the region (correct casing)
* Create a new RentRegion.
* @param name The name of the region (correct casing)
* @param world The world of the WorldGuard region
*/
public RentRegion(String name, World world) {
super(name, world);
}
@Override
public RegionType getType() {
return RegionType.RENT;
}
@Override
public RegionState getState() {
if(isRented()) {
@ -56,14 +56,14 @@ public class RentRegion extends GeneralRegion {
return RegionState.FORRENT;
}
}
@Override
public boolean isAvailable() {
return !isRented();
}
/**
* Get the UUID of the player renting the region
* Get the UUID of the player renting the region.
* @return The UUID of the renter
*/
public UUID getRenter() {
@ -77,22 +77,23 @@ public class RentRegion extends GeneralRegion {
}
return null;
}
/**
* Check if a player is the renter of this region
* Check if a player is the renter of this region.
* @param player Player to check
* @return true if this player rents this region, otherwise false
*/
public boolean isRenter(Player player) {
return player != null && isRenter(player.getUniqueId());
}
public boolean isRenter(UUID player) {
UUID renter = getRenter();
return !(player == null || renter == null) && renter.equals(player);
}
/**
* Set the renter of this region
* Set the renter of this region.
* @param renter The UUID of the player that should be set as the renter
*/
public void setRenter(UUID renter) {
@ -104,25 +105,25 @@ public class RentRegion extends GeneralRegion {
setSetting("rent.renterName", Utils.toName(renter));
}
}
/**
* Get the max number of extends of this region
* Get the max number of extends of this region.
* @return -1 if infinite otherwise the maximum number
*/
public int getMaxExtends() {
return getIntegerSetting("rent.maxExtends");
}
/**
* Get how many times the rent has already been extended
* Get how many times the rent has already been extended.
* @return The number of times extended
*/
public int getTimesExtended() {
return config.getInt("rent.timesExtended");
}
/**
* Set the number of times the region has been extended
* Set the number of times the region has been extended.
* @param times The number of times the region has been extended
*/
public void setTimesExtended(int times) {
@ -157,13 +158,13 @@ public class RentRegion extends GeneralRegion {
case AreaShop.tagRawMoneyBackAmount:
return getMoneyBackAmount();
case AreaShop.tagMoneyBackPercentage:
return getMoneyBackPercentage()%1.0 == 0.0 ? (int)getMoneyBackPercentage() : getMoneyBackPercentage();
return getMoneyBackPercentage() % 1.0 == 0.0 ? (int)getMoneyBackPercentage() : getMoneyBackPercentage();
case AreaShop.tagTimesExtended:
return this.getTimesExtended();
case AreaShop.tagMaxExtends:
return this.getMaxExtends();
case AreaShop.tagExtendsLeft:
return getMaxExtends()-getTimesExtended();
return getMaxExtends() - getTimesExtended();
case AreaShop.tagMaxRentTime:
return millisToHumanFormat(getMaxRentTime());
case AreaShop.tagMaxInactiveTime:
@ -173,17 +174,17 @@ public class RentRegion extends GeneralRegion {
return super.provideReplacement(variable);
}
}
/**
* Check if the region is rented
* Check if the region is rented.
* @return true if the region is rented, otherwise false
*/
public boolean isRented() {
return getRenter() != null;
}
/**
* Get the name of the player renting this region
* Get the name of the player renting this region.
* @return Name of the player renting this region, if unavailable by UUID it will return the old cached name, if that is unavailable it will return &lt;UNKNOWN&gt;
*/
public String getPlayerName() {
@ -196,17 +197,17 @@ public class RentRegion extends GeneralRegion {
}
return result;
}
/**
* Get the time until this region is rented (time from 1970 epoch)
* Get the time until this region is rented (time from 1970 epoch).
* @return The epoch time until which this region is rented
*/
public long getRentedUntil() {
return getLongSetting("rent.rentedUntil");
}
/**
* Set the time until the region is rented (milliseconds from 1970, system time)
* Set the time until the region is rented (milliseconds from 1970, system time).
* @param rentedUntil The time until the region is rented
*/
public void setRentedUntil(Long rentedUntil) {
@ -216,17 +217,17 @@ public class RentRegion extends GeneralRegion {
setSetting("rent.rentedUntil", rentedUntil);
}
}
/**
* Get the price of the region
* Get the price of the region.
* @return The price of the region
*/
public double getPrice() {
return Math.max(0, Utils.evaluateToDouble(getStringSetting("rent.price"), this));
}
/**
* Get the formatted string of the price (includes prefix and suffix)
* Get the formatted string of the price (includes prefix and suffix).
* @return The formatted string of the price
*/
public String getFormattedPrice() {
@ -234,23 +235,23 @@ public class RentRegion extends GeneralRegion {
}
/**
* Get the duration of 1 rent period
* Get the duration of 1 rent period.
* @return The duration in milliseconds of 1 rent period
*/
public long getDuration() {
return Utils.durationStringToLong(getDurationString());
}
/**
* Get the duration string, includes 'number indentifier'
* Get the duration string, includes 'number indentifier'.
* @return The duration string
*/
public String getDurationString() {
return getStringSetting("rent.duration");
}
/**
* Get the time that is left on the region
* Get the time that is left on the region.
* @return The time left on the region
*/
public long getTimeLeft() {
@ -260,93 +261,93 @@ public class RentRegion extends GeneralRegion {
return 0;
}
}
/**
* Get a formatted string indicating the rent time that is left
* Get a formatted string indicating the rent time that is left.
* @return Time left on the rent, for example '29 days', '3 months', '1 second'
*/
public String getTimeLeftString() {
return Utils.millisToHumanFormat(getTimeLeft());
}
/**
* Minutes until automatic unrent when player is offline
* Minutes until automatic unrent when player is offline.
* @return The number of milliseconds until the region is unrented while player is offline
*/
public long getInactiveTimeUntilUnrent() {
return Utils.getDurationFromMinutesOrStringInput(getStringSetting("rent.inactiveTimeUntilUnrent"));
}
/**
* Get a human readable string indicating how long the player can be offline until automatic unrent
* Get a human readable string indicating how long the player can be offline until automatic unrent.
* @return String indicating the inactive time until unrent
*/
public String getFormattedInactiveTimeUntilUnrent() {
return Utils.millisToHumanFormat(getInactiveTimeUntilUnrent());
}
/**
* Change the price of the region
* Change the price of the region.
* @param price The price of the region
*/
public void setPrice(double price) {
setSetting("rent.price", price);
}
/**
* Remove the price so that the price will be taken from a group or the default.yml file
*/
public void removePrice() {
setSetting("rent.price", null);
}
/**
* Set the duration of the rent
* Set the duration of the rent.
* @param duration The duration of the rent (as specified on the documentation pages)
*/
public void setDuration(String duration) {
setSetting("rent.duration", duration);
}
/**
* Get the moneyBack percentage
* Get the moneyBack percentage.
* @return The % of money the player will get back when unrenting
*/
public double getMoneyBackPercentage() {
return Utils.evaluateToDouble(getStringSetting("rent.moneyBack"), this);
}
/**
* Get the amount of money that should be paid to the player when unrenting the region
* Get the amount of money that should be paid to the player when unrenting the region.
* @return The amount of money the player should get back
*/
public double getMoneyBackAmount() {
Long currentTime = Calendar.getInstance().getTimeInMillis();
Double timeLeft = (double) ((getRentedUntil() - currentTime));
Double timeLeft = (double)((getRentedUntil() - currentTime));
double percentage = (getMoneyBackPercentage()) / 100.0;
Double timePeriod = (double) (getDuration());
Double timePeriod = (double)(getDuration());
double periods = timeLeft / timePeriod;
return Math.max(0, periods*getPrice()*percentage);
return Math.max(0, periods * getPrice() * percentage);
}
/**
* Get the formatted string of the amount of the moneyBack amount
* Get the formatted string of the amount of the moneyBack amount.
* @return String with currency symbols and proper fractional part
*/
public String getFormattedMoneyBackAmount() {
return Utils.formatCurrency(getMoneyBackAmount());
}
/**
* Get the maximum time the player can rent the region in advance (milliseconds)
* Get the maximum time the player can rent the region in advance (milliseconds).
* @return The maximum rent time in milliseconds
*/
public long getMaxRentTime() {
return Utils.getDurationFromMinutesOrStringInput(getStringSetting("rent.maxRentTime"));
}
/**
* Check if the rent should expire
* Check if the rent should expire.
* @return true if the rent has expired and has been unrented, false otherwise
*/
public boolean checkExpiration() {
@ -363,10 +364,10 @@ public class RentRegion extends GeneralRegion {
}
return false;
}
/**
* Send the expiration warnings from the selected profile which is specified in the config
* Sends all warnings since previous call until (now + normal delay), delay can be found in the config as well
* Send the expiration warnings from the selected profile which is specified in the config.
* Sends all warnings since previous call until (now + normal delay), delay can be found in the config as well.
*/
public void sendExpirationWarnings() {
// Send from warningsDoneUntil to current+delay
@ -380,13 +381,13 @@ public class RentRegion extends GeneralRegion {
// Check if a warning needs to be send for each defined point in time
Player player = Bukkit.getPlayer(getRenter());
long sendUntil = Calendar.getInstance().getTimeInMillis()+(plugin.getConfig().getInt("expireWarning.delay")*60*1000);
long sendUntil = Calendar.getInstance().getTimeInMillis() + (plugin.getConfig().getInt("expireWarning.delay") * 60 * 1000);
for(String timeBefore : profileSection.getKeys(false)) {
long timeBeforeParsed = Utils.durationStringToLong(timeBefore);
if(timeBeforeParsed <= 0) {
return;
}
long checkTime = getRentedUntil()-timeBeforeParsed;
long checkTime = getRentedUntil() - timeBeforeParsed;
if(checkTime > warningsDoneUntil && checkTime <= sendUntil) {
List<String> commands;
@ -396,9 +397,9 @@ public class RentRegion extends GeneralRegion {
* warnPlayer: true
* commands: ["say hi"]
*/
commands = profileSection.getStringList(timeBefore+".commands");
commands = profileSection.getStringList(timeBefore + ".commands");
// Warn player
if(profileSection.getBoolean(timeBefore+".warnPlayer") && player != null) {
if(profileSection.getBoolean(timeBefore + ".warnPlayer") && player != null) {
message(player, "rent-expireWarning", this);
}
} else {
@ -409,9 +410,9 @@ public class RentRegion extends GeneralRegion {
}
warningsDoneUntil = sendUntil;
}
/**
* Rent a region
* Rent a region.
* @param player The player that wants to rent the region
* @return true if it succeeded and false if not
*/
@ -430,7 +431,7 @@ public class RentRegion extends GeneralRegion {
if(getRegion() == null) {
message(player, "general-noRegion");
return false;
}
}
boolean extend = false;
if(getRenter() != null && player.getUniqueId().equals(getRenter())) {
extend = true;
@ -438,7 +439,7 @@ public class RentRegion extends GeneralRegion {
// Check if the region is available for renting or if the player wants to extend the rent
if(!isRented() || extend) {
// Check if the players needs to be in the world or region for buying
if(restrictedToRegion() && (!player.getWorld().getName().equals(getWorldName())
if(restrictedToRegion() && (!player.getWorld().getName().equals(getWorldName())
|| !getRegion().contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()))) {
message(player, "rent-restrictedToRegion");
return false;
@ -446,7 +447,7 @@ public class RentRegion extends GeneralRegion {
if(restrictedToWorld() && !player.getWorld().getName().equals(getWorldName())) {
message(player, "rent-restrictedToWorld", player.getWorld().getName());
return false;
}
}
// Check region limits if this is not extending
if(!(extend && config.getBoolean("allowRegionExtendsWhenAboveLimits"))) {
@ -473,7 +474,7 @@ public class RentRegion extends GeneralRegion {
return false;
}
}
// Check if the player can still extend this rent
if(extend && !player.hasPermission("areashop.rentextendbypass")) {
if(getMaxExtends() >= 0 && getTimesExtended() >= getMaxExtends()) {
@ -481,7 +482,7 @@ public class RentRegion extends GeneralRegion {
return false;
}
}
// Check if there is enough time left before hitting maxRentTime
boolean extendToMax = false;
double price = getPrice();
@ -491,7 +492,7 @@ public class RentRegion extends GeneralRegion {
if(isRented()) {
timeRented = getRentedUntil() - timeNow;
}
if((timeRented + getDuration()) > (maxRentTime)
if((timeRented + getDuration()) > (maxRentTime)
&& !player.hasPermission("areashop.renttimebypass")
&& maxRentTime != -1) {
// Extend to the maximum instead of adding a full period
@ -502,7 +503,7 @@ public class RentRegion extends GeneralRegion {
} else {
long toRentPart = maxRentTime - timeRented;
extendToMax = true;
price = ((double)toRentPart)/getDuration()*price;
price = ((double)toRentPart) / getDuration() * price;
}
} else {
message(player, "rent-maxRentTime");
@ -539,10 +540,10 @@ public class RentRegion extends GeneralRegion {
r = plugin.getEconomy().depositPlayer(landlordName, getWorldName(), price);
}
if(r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '"+landlordName+"' "+Utils.formatCurrency(price)+" for his rent of region "+getName()+" to "+player.getName());
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + Utils.formatCurrency(price) + " for his rent of region " + getName() + " to " + player.getName());
}
}
if(!extend) {
// Run commands
runEventCommands(RegionEvent.RENTED, true);
@ -550,13 +551,13 @@ public class RentRegion extends GeneralRegion {
// Run commands
runEventCommands(RegionEvent.EXTENDED, true);
}
// Get the time until the region will be rented
Calendar calendar = Calendar.getInstance();
if(extendToMax) {
calendar.setTimeInMillis(calendar.getTimeInMillis() + getMaxRentTime());
} else if(extend) {
calendar.setTimeInMillis(getRentedUntil()+getDuration());
calendar.setTimeInMillis(getRentedUntil() + getDuration());
} else {
calendar.setTimeInMillis(calendar.getTimeInMillis() + getDuration());
}
@ -576,7 +577,7 @@ public class RentRegion extends GeneralRegion {
// Notify about updates
this.notifyAndUpdate(new RentedRegionEvent(this, extend));
// Send message to the player
if(extendToMax) {
message(player, "rent-extendedToMax");
@ -603,17 +604,17 @@ public class RentRegion extends GeneralRegion {
}
} else {
message(player, "rent-someoneElse");
}
}
} else {
message(player, "rent-noPermission");
}
return false;
}
/**
* Unrent a region, reset to unrented
* Unrent a region, reset to unrented.
* @param giveMoneyBack true if money should be given back to the player, false otherwise
* @param executor The CommandSender that should get the cancelled message if there is any, or null
* @param executor The CommandSender that should get the cancelled message if there is any, or null
* @return true if unrenting succeeded, othwerwise false
*/
@SuppressWarnings("deprecation")
@ -644,7 +645,7 @@ public class RentRegion extends GeneralRegion {
// Run commands
this.runEventCommands(RegionEvent.UNRENTED, true);
double moneyBack = getMoneyBackAmount();
double moneyBack = getMoneyBackAmount();
if(moneyBack > 0 && giveMoneyBack) {
boolean noPayBack = false;
OfflinePlayer landlordPlayer = null;
@ -662,8 +663,8 @@ public class RentRegion extends GeneralRegion {
if(r == null || !r.transactionSuccess()) {
noPayBack = true;
}
}
}
// Give back the money
OfflinePlayer player = Bukkit.getOfflinePlayer(getRenter());
if(player != null && !noPayBack) {
@ -679,7 +680,7 @@ public class RentRegion extends GeneralRegion {
error = true;
}
if(error || r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying back to "+getPlayerName()+" money while unrenting region "+getName());
AreaShop.warn("Something went wrong with paying back to " + getPlayerName() + " money while unrenting region " + getName());
}
}
}
@ -705,7 +706,7 @@ public class RentRegion extends GeneralRegion {
this.runEventCommands(RegionEvent.UNRENTED, false);
return true;
}
@Override
public boolean checkInactive() {
if(isDeleted() || !isRented()) {
@ -719,8 +720,8 @@ public class RentRegion extends GeneralRegion {
long lastPlayed = getLastActiveTime();
//AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
if(Calendar.getInstance().getTimeInMillis() > (lastPlayed + inactiveSetting)) {
AreaShop.info("Region "+getName()+" unrented because of inactivity for player "+getPlayerName());
AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
AreaShop.info("Region " + getName() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis() - player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
return this.unRent(true, null);
}
return false;

View File

@ -10,132 +10,136 @@ import java.util.HashMap;
public class Analytics {
/**
* Start analytics tracking
*/
public static void start() {
// Legacy MCstats statistics (remove at some point)
try {
new me.wiefferink.areashop.lib.Metrics(AreaShop.getInstance()).start();
AreaShop.debug("Started mcstats.org statistics service");
} catch (Exception e) {
AreaShop.debug("Could not start mcstats.org statistics service");
}
/**
* Start analytics tracking.
*/
public static void start() {
// Legacy MCstats statistics (remove at some point)
try {
new me.wiefferink.areashop.lib.Metrics(AreaShop.getInstance()).start();
AreaShop.debug("Started mcstats.org statistics service");
} catch(Exception e) {
AreaShop.debug("Could not start mcstats.org statistics service");
}
// bStats statistics
try {
Metrics metrics = new Metrics(AreaShop.getInstance());
// bStats statistics
try {
Metrics metrics = new Metrics(AreaShop.getInstance());
// Number of regions
metrics.addCustomChart(new Metrics.SingleLineChart("region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getRegions().size();
}
});
// Number of regions
metrics.addCustomChart(new Metrics.SingleLineChart("region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getRegions().size();
}
});
// Number of rental regions
metrics.addCustomChart(new Metrics.SingleLineChart("rental_region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getRents().size();
}
});
// Number of rental regions
metrics.addCustomChart(new Metrics.SingleLineChart("rental_region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getRents().size();
}
});
// Number of buy regions
metrics.addCustomChart(new Metrics.SingleLineChart("buy_region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getBuys().size();
}
});
// Number of buy regions
metrics.addCustomChart(new Metrics.SingleLineChart("buy_region_count") {
@Override
public int getValue() {
return AreaShop.getInstance().getFileManager().getBuys().size();
}
});
// Language
metrics.addCustomChart(new Metrics.SimplePie("language") {
@Override
public String getValue() {
return AreaShop.getInstance().getConfig().getString("language");
}
});
// Language
metrics.addCustomChart(new Metrics.SimplePie("language") {
@Override
public String getValue() {
return AreaShop.getInstance().getConfig().getString("language");
}
});
// Pie with region states
metrics.addCustomChart(new Metrics.AdvancedPie("region_state") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> result) {
RegionStateStats stats = getStateStats();
result.put("For Rent", stats.forrent);
result.put("Rented", stats.rented);
result.put("For Sale", stats.forsale);
result.put("Sold", stats.sold);
result.put("Reselling", stats.reselling);
return result;
}
});
// Pie with region states
metrics.addCustomChart(new Metrics.AdvancedPie("region_state") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> result) {
RegionStateStats stats = getStateStats();
result.put("For Rent", stats.forrent);
result.put("Rented", stats.rented);
result.put("For Sale", stats.forsale);
result.put("Sold", stats.sold);
result.put("Reselling", stats.reselling);
return result;
}
});
// Time series of each region state
metrics.addCustomChart(new Metrics.SingleLineChart("forrent_region_count") {
@Override
public int getValue() {
return getStateStats().forrent;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("rented_region_count") {
@Override
public int getValue() {
return getStateStats().rented;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("forsale_region_count") {
@Override
public int getValue() {
return getStateStats().forsale;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("sold_region_count") {
@Override
public int getValue() {
return getStateStats().sold;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("reselling_region_count") {
@Override
public int getValue() {
return getStateStats().reselling;
}
});
// Time series of each region state
metrics.addCustomChart(new Metrics.SingleLineChart("forrent_region_count") {
@Override
public int getValue() {
return getStateStats().forrent;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("rented_region_count") {
@Override
public int getValue() {
return getStateStats().rented;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("forsale_region_count") {
@Override
public int getValue() {
return getStateStats().forsale;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("sold_region_count") {
@Override
public int getValue() {
return getStateStats().sold;
}
});
metrics.addCustomChart(new Metrics.SingleLineChart("reselling_region_count") {
@Override
public int getValue() {
return getStateStats().reselling;
}
});
AreaShop.debug("Started bstats.org statistics service");
} catch (Exception e) {
AreaShop.debug("Could not start bstats.org statistics service");
}
}
AreaShop.debug("Started bstats.org statistics service");
} catch(Exception e) {
AreaShop.debug("Could not start bstats.org statistics service");
}
}
private static class RegionStateStats {
int forrent = 0, forsale = 0, rented = 0, sold = 0, reselling = 0;
}
private static class RegionStateStats {
int forrent = 0;
int forsale = 0;
int rented = 0;
int sold = 0;
int reselling = 0;
}
private static RegionStateStats getStateStats() {
RegionStateStats result = new RegionStateStats();
for (GeneralRegion region : AreaShop.getInstance().getFileManager().getRegions()) {
if (region instanceof RentRegion) {
RentRegion rent = (RentRegion) region;
if (rent.isAvailable()) {
result.forrent++;
} else {
result.rented++;
}
} else if (region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion) region;
if (buy.isAvailable()) {
result.forsale++;
} else if (buy.isInResellingMode()) {
result.reselling++;
} else {
result.sold++;
}
}
}
return result;
}
private static RegionStateStats getStateStats() {
RegionStateStats result = new RegionStateStats();
for(GeneralRegion region : AreaShop.getInstance().getFileManager().getRegions()) {
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isAvailable()) {
result.forrent++;
} else {
result.rented++;
}
} else if(region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
if(buy.isAvailable()) {
result.forsale++;
} else if(buy.isInResellingMode()) {
result.reselling++;
} else {
result.sold++;
}
}
}
return result;
}
}

View File

@ -11,7 +11,11 @@ import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.interactivemessenger.processing.Message;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.bukkit.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
@ -23,12 +27,20 @@ import javax.script.ScriptException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class Utils {
// Not used
private Utils() {}
private Utils() {
}
private static YamlConfiguration config;
private static ArrayList<String> identifiers;
@ -41,6 +53,10 @@ public class Utils {
private static ArrayList<String> years;
private static ScriptEngine scriptEngine;
/**
* Initialize the utilities class with constants.
* @param pluginConfig The config of the plugin
*/
public static void initialize(YamlConfiguration pluginConfig) {
config = pluginConfig;
@ -64,9 +80,9 @@ public class Utils {
}
/**
* Create a message with a list of parts
* Create a message with a list of parts.
* @param replacements The parts to use
* @param messagePart The message to use for the parts
* @param messagePart The message to use for the parts
* @return A Message object containing the parts combined into one message
*/
public static Message combinedMessage(Collection<?> replacements, String messagePart) {
@ -74,9 +90,9 @@ public class Utils {
}
/**
* Create a message with a list of parts
* Create a message with a list of parts.
* @param replacements The parts to use
* @param messagePart The message to use for the parts
* @param messagePart The message to use for the parts
* @param combiner The string to use as combiner
* @return A Message object containing the parts combined into one message
*/
@ -95,7 +111,7 @@ public class Utils {
}
/**
* Gets the online players
* Gets the online players.
* Provides backwards compatibility for 1.7- where it returns an array
* @return Online players
*/
@ -109,14 +125,14 @@ public class Utils {
return Arrays.asList((Player[])onlinePlayerMethod.invoke(Bukkit.getServer()));
}
} catch(Exception ex) {
AreaShop.debug("getOnlinePlayers error: "+ex.getMessage());
AreaShop.debug("getOnlinePlayers error: " + ex.getMessage());
}
return new HashSet<>();
}
/**
* Create a map from a location, to save it in the config
* @param location The location to transform
* Create a map from a location, to save it in the config.
* @param location The location to transform
* @param setPitchYaw true to save the pitch and yaw, otherwise false
* @return The map with the location values
*/
@ -131,22 +147,22 @@ public class Utils {
result.set("z", location.getZ());
if(setPitchYaw) {
result.set("yaw", Float.toString(location.getYaw()));
result.set("pitch", Float.toString(location.getPitch()));
result.set("pitch", Float.toString(location.getPitch()));
}
return result;
}
/**
* Create a map from a location, to save it in the config (without pitch and yaw)
* Create a map from a location, to save it in the config (without pitch and yaw).
* @param location The location to transform
* @return The map with the location values
*/
public static ConfigurationSection locationToConfig(Location location) {
return locationToConfig(location, false);
}
/**
* Create a location from a map, reconstruction from the config values
* Create a location from a map, reconstruction from the config values.
* @param config The config section to reconstruct from
* @return The location
*/
@ -170,9 +186,9 @@ public class Utils {
}
return result;
}
/**
* Create a comma-separated list
* Create a comma-separated list.
* @param input Collection of object which should be concatenated with comma's in between
* @return Innput object concatenated with comma's in between
*/
@ -188,28 +204,28 @@ public class Utils {
result += ", " + object.toString();
}
}
}
}
return result;
}
/**
* Convert milliseconds to ticks
* Convert milliseconds to ticks.
* @param milliseconds Milliseconds to convert
* @return milliseconds divided by 50 (20 ticks per second)
*/
public static long millisToTicks(long milliseconds) {
return milliseconds/50;
return milliseconds / 50;
}
/**
* Convert milliseconds to a human readable format
* Convert milliseconds to a human readable format.
* @param milliseconds The amount of milliseconds to convert
* @return A formatted string based on the language file
*/
public static String millisToHumanFormat(long milliseconds) {
long timeLeft = milliseconds+500;
long timeLeft = milliseconds + 500;
// To seconds
timeLeft = timeLeft/1000;
timeLeft = timeLeft / 1000;
if(timeLeft <= 0) {
return Message.fromKey("timeleft-ended").getPlain();
} else if(timeLeft == 1) {
@ -218,52 +234,53 @@ public class Utils {
return Message.fromKey("timeleft-seconds").replacements(timeLeft).getPlain();
}
// To minutes
timeLeft = timeLeft/60;
timeLeft = timeLeft / 60;
if(timeLeft <= 120) {
return Message.fromKey("timeleft-minutes").replacements(timeLeft).getPlain();
}
// To hours
timeLeft = timeLeft/60;
timeLeft = timeLeft / 60;
if(timeLeft <= 48) {
return Message.fromKey("timeleft-hours").replacements(timeLeft).getPlain();
}
// To days
timeLeft = timeLeft/24;
timeLeft = timeLeft / 24;
if(timeLeft <= 60) {
return Message.fromKey("timeleft-days").replacements(timeLeft).getPlain();
}
// To months
timeLeft = timeLeft/30;
timeLeft = timeLeft / 30;
if(timeLeft <= 24) {
return Message.fromKey("timeleft-months").replacements(timeLeft).getPlain();
}
// To years
timeLeft = timeLeft/12;
timeLeft = timeLeft / 12;
return Message.fromKey("timeleft-years").replacements(timeLeft).getPlain();
}
private static final BlockFace[] facings = {BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.EAST, BlockFace.SOUTH_EAST, BlockFace.SOUTH, BlockFace.SOUTH_WEST, BlockFace.WEST, BlockFace.NORTH_WEST};
/**
* Get the facing direction based on the yaw
* @param yaw The horizontal angle that for example the player is looking
* @return The Block Face of the angle
*/
* Get the facing direction based on the yaw.
* @param yaw The horizontal angle that for example the player is looking
* @return The Block Face of the angle
*/
public static BlockFace yawToFacing(float yaw) {
return facings[Math.round(yaw / 45f) & 0x7];
}
// ======================================================================
// Methods to get WorldGuard or AreaShop regions by location or selection
// ======================================================================
/**
* Get all AreaShop regions intersecting with a WorldEdit selection
* Get all AreaShop regions intersecting with a WorldEdit selection.
* @param selection The selection to check
* @return A list with all the AreaShop regions intersecting with the selection
*/
public static List<GeneralRegion> getASRegionsInSelection(Selection selection) {
public static List<GeneralRegion> getRegionsInSelection(Selection selection) {
ArrayList<GeneralRegion> result = new ArrayList<>();
for(ProtectedRegion region : getWERegionsInSelection(selection)) {
for(ProtectedRegion region : getWorldEditRegionsInSelection(selection)) {
GeneralRegion asRegion = AreaShop.getInstance().getFileManager().getRegion(region.getId());
if(asRegion != null) {
result.add(asRegion);
@ -271,22 +288,23 @@ public class Utils {
}
return result;
}
/**
* Get all AreaShop regions containing a location
* Get all AreaShop regions containing a location.
* @param location The location to check
* @return A list with all the AreaShop regions that contain the location
*/
public static List<GeneralRegion> getASRegionsByLocation(Location location) {
public static List<GeneralRegion> getRegions(Location location) {
Selection selection = new CuboidSelection(location.getWorld(), location, location);
return getASRegionsInSelection(selection);
return getRegionsInSelection(selection);
}
/**
* Get all WorldGuard regions intersecting with a WorldEdit selection
* Get all WorldGuard regions intersecting with a WorldEdit selection.
* @param selection The selection to check
* @return A list with all the WorldGuard regions intersecting with the selection
*/
public static List<ProtectedRegion> getWERegionsInSelection(Selection selection) {
public static List<ProtectedRegion> getWorldEditRegionsInSelection(Selection selection) {
// Get all regions inside or intersecting with the WorldEdit selection of the player
World world = selection.getWorld();
RegionManager regionManager = AreaShop.getInstance().getWorldGuard().getRegionManager(world);
@ -295,38 +313,38 @@ public class Utils {
Location selectionMax = selection.getMaximumPoint();
for(ProtectedRegion region : regionManager.getRegions().values()) {
BlockVector regionMin = region.getMinimumPoint();
BlockVector regionMax = region.getMaximumPoint();
if(
BlockVector regionMax = region.getMaximumPoint();
if(
( // x part, resolves to true if the selection and region overlap anywhere on the x-axis
(regionMin.getBlockX() <= selectionMax.getBlockX() && regionMin.getBlockX() >= selectionMin.getBlockX())
|| (regionMax.getBlockX() <= selectionMax.getBlockX() && regionMax.getBlockX() >= selectionMin.getBlockX())
|| (selectionMin.getBlockX() >= regionMin.getBlockX() && selectionMin.getBlockX() <= regionMax.getBlockX())
|| (selectionMax.getBlockX() >= regionMin.getBlockX() && selectionMax.getBlockX() <= regionMax.getBlockX())
(regionMin.getBlockX() <= selectionMax.getBlockX() && regionMin.getBlockX() >= selectionMin.getBlockX())
|| (regionMax.getBlockX() <= selectionMax.getBlockX() && regionMax.getBlockX() >= selectionMin.getBlockX())
|| (selectionMin.getBlockX() >= regionMin.getBlockX() && selectionMin.getBlockX() <= regionMax.getBlockX())
|| (selectionMax.getBlockX() >= regionMin.getBlockX() && selectionMax.getBlockX() <= regionMax.getBlockX())
) && ( // Y part, resolves to true if the selection and region overlap anywhere on the y-axis
(regionMin.getBlockY() <= selectionMax.getBlockY() && regionMin.getBlockY() >= selectionMin.getBlockY())
|| (regionMax.getBlockY() <= selectionMax.getBlockY() && regionMax.getBlockY() >= selectionMin.getBlockY())
|| (selectionMin.getBlockY() >= regionMin.getBlockY() && selectionMin.getBlockY() <= regionMax.getBlockY())
|| (selectionMax.getBlockY() >= regionMin.getBlockY() && selectionMax.getBlockY() <= regionMax.getBlockY())
(regionMin.getBlockY() <= selectionMax.getBlockY() && regionMin.getBlockY() >= selectionMin.getBlockY())
|| (regionMax.getBlockY() <= selectionMax.getBlockY() && regionMax.getBlockY() >= selectionMin.getBlockY())
|| (selectionMin.getBlockY() >= regionMin.getBlockY() && selectionMin.getBlockY() <= regionMax.getBlockY())
|| (selectionMax.getBlockY() >= regionMin.getBlockY() && selectionMax.getBlockY() <= regionMax.getBlockY())
) && ( // Z part, resolves to true if the selection and region overlap anywhere on the z-axis
(regionMin.getBlockZ() <= selectionMax.getBlockZ() && regionMin.getBlockZ() >= selectionMin.getBlockZ())
|| (regionMax.getBlockZ() <= selectionMax.getBlockZ() && regionMax.getBlockZ() >= selectionMin.getBlockZ())
|| (selectionMin.getBlockZ() >= regionMin.getBlockZ() && selectionMin.getBlockZ() <= regionMax.getBlockZ())
|| (selectionMax.getBlockZ() >= regionMin.getBlockZ() && selectionMax.getBlockZ() <= regionMax.getBlockZ())
(regionMin.getBlockZ() <= selectionMax.getBlockZ() && regionMin.getBlockZ() >= selectionMin.getBlockZ())
|| (regionMax.getBlockZ() <= selectionMax.getBlockZ() && regionMax.getBlockZ() >= selectionMin.getBlockZ())
|| (selectionMin.getBlockZ() >= regionMin.getBlockZ() && selectionMin.getBlockZ() <= regionMax.getBlockZ())
|| (selectionMax.getBlockZ() >= regionMin.getBlockZ() && selectionMax.getBlockZ() <= regionMax.getBlockZ())
)
) {
) {
result.add(region);
}
}
return result;
}
/**
* Get a list of regions around a location
* - Returns highest priority, child instead of parent regions
* Get a list of regions around a location.
* - Returns highest priority, child instead of parent regions
* @param location The location to check for regions
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<ProtectedRegion> getApplicableRegions(Location location) {
public static List<ProtectedRegion> getImportantWorldEditRegions(Location location) {
List<ProtectedRegion> result = new ArrayList<>();
Set<ProtectedRegion> regions = AreaShop.getInstance().getWorldGuardHandler().getApplicableRegionsSet(location);
if(regions != null) {
@ -352,51 +370,51 @@ public class Utils {
}
/**
* Get the most important rental AreaShop regions
* - Returns highest priority, child instead of parent regions
* Get the most important rental AreaShop regions.
* - Returns highest priority, child instead of parent regions.
* @param location The location to check for regions
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<RentRegion> getApplicableRentRegions(Location location) {
public static List<RentRegion> getImportantRentRegions(Location location) {
List<RentRegion> result = new ArrayList<>();
for(GeneralRegion region : getApplicableASRegions(location, GeneralRegion.RegionType.RENT)) {
for(GeneralRegion region : getImportantRegions(location, GeneralRegion.RegionType.RENT)) {
result.add((RentRegion)region);
}
return result;
}
/**
* Get the most important buy AreaShop regions
* - Returns highest priority, child instead of parent regions
* Get the most important buy AreaShop regions.
* - Returns highest priority, child instead of parent regions.
* @param location The location to check for regions
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<BuyRegion> getApplicableBuyRegions(Location location) {
public static List<BuyRegion> getImportantBuyRegions(Location location) {
List<BuyRegion> result = new ArrayList<>();
for(GeneralRegion region : getApplicableASRegions(location, GeneralRegion.RegionType.BUY)) {
for(GeneralRegion region : getImportantRegions(location, GeneralRegion.RegionType.BUY)) {
result.add((BuyRegion)region);
}
return result;
}
/**
* Get the most important AreaShop regions
* - Returns highest priority, child instead of parent regions
* Get the most important AreaShop regions.
* - Returns highest priority, child instead of parent regions.
* @param location The location to check for regions
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<GeneralRegion> getAllApplicableRegions(Location location) {
return getApplicableASRegions(location, null);
public static List<GeneralRegion> getImportantRegions(Location location) {
return getImportantRegions(location, null);
}
/**
* Get the most important AreaShop regions
* - Returns highest priority, child instead of parent regions
* Get the most important AreaShop regions.
* - Returns highest priority, child instead of parent regions.
* @param location The location to check for regions
* @param type The type of regions to look for, null for all
* @param type The type of regions to look for, null for all
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<GeneralRegion> getApplicableASRegions(Location location, GeneralRegion.RegionType type) {
public static List<GeneralRegion> getImportantRegions(Location location, GeneralRegion.RegionType type) {
List<GeneralRegion> result = new ArrayList<>();
Set<ProtectedRegion> regions = AreaShop.getInstance().getWorldGuardHandler().getApplicableRegionsSet(location);
if(regions != null) {
@ -404,12 +422,12 @@ public class Utils {
for(ProtectedRegion pr : regions) {
GeneralRegion region = AreaShop.getInstance().getFileManager().getRegion(pr.getId());
if(region != null && (
(type == GeneralRegion.RegionType.RENT && region instanceof RentRegion)
|| (type == GeneralRegion.RegionType.BUY && region instanceof BuyRegion)
|| type == null)) {
(type == GeneralRegion.RegionType.RENT && region instanceof RentRegion)
|| (type == GeneralRegion.RegionType.BUY && region instanceof BuyRegion)
|| type == null)) {
candidates.add(region);
}
}
}
boolean first = true;
for(GeneralRegion region : candidates) {
if(region == null) {
@ -437,7 +455,7 @@ public class Utils {
/**
* Convert color and formatting codes to bukkit values
* Convert color and formatting codes to bukkit values.
* @param input Start string with color and formatting codes in it
* @return String with the color and formatting codes in the bukkit format
*/
@ -451,15 +469,15 @@ public class Utils {
/**
* Format the currency amount with the characters before and after
* Format the currency amount with the characters before and after.
* @param amount Amount of money to format
* @return Currency character format string
*/
public static String formatCurrency(double amount) {
String before = config.getString("moneyCharacter");
before = before.replace(AreaShop.currencyEuro, "\u20ac");
before = before.replace(AreaShop.currencyEuro, "");
String after = config.getString("moneyCharacterAfter");
after = after.replace(AreaShop.currencyEuro, "\u20ac");
after = after.replace(AreaShop.currencyEuro, "");
String result;
// Check for infinite and NaN
if(Double.isInfinite(amount)) {
@ -471,34 +489,34 @@ public class Utils {
double metricAbove = config.getDouble("metricSuffixesAbove");
if(metricAbove != -1 && amount >= metricAbove) {
if(amount >= 1000000000000000000000000.0) {
amount = amount/1000000000000000000000000.0;
after = "Y"+after;
amount = amount / 1000000000000000000000000.0;
after = "Y" + after;
} else if(amount >= 1000000000000000000000.0) {
amount = amount/1000000000000000000000.0;
after = "Z"+after;
amount = amount / 1000000000000000000000.0;
after = "Z" + after;
} else if(amount >= 1000000000000000000.0) {
amount = amount/1000000000000000000.0;
after = "E"+after;
amount = amount / 1000000000000000000.0;
after = "E" + after;
} else if(amount >= 1000000000000000.0) {
amount = amount/1000000000000000.0;
after = "P"+after;
amount = amount / 1000000000000000.0;
after = "P" + after;
} else if(amount >= 1000000000000.0) {
amount = amount/1000000000000.0;
after = "T"+after;
amount = amount / 1000000000000.0;
after = "T" + after;
} else if(amount >= 1000000000.0) {
amount = amount/1000000000.0;
after = "G"+after;
amount = amount / 1000000000.0;
after = "G" + after;
} else if(amount >= 1000000.0) {
amount = amount/1000000.0;
after = "M"+after;
amount = amount / 1000000.0;
after = "M" + after;
} else if(amount >= 1000.0) {
amount = amount/1000.0;
after = "k"+after;
amount = amount / 1000.0;
after = "k" + after;
}
BigDecimal bigDecimal = new BigDecimal(amount);
if(bigDecimal.toString().contains(".")) {
int frontLength = bigDecimal.toString().substring(0, bigDecimal.toString().indexOf('.')).length();
bigDecimal = bigDecimal.setScale(config.getInt("fractionalNumbers")+(3-frontLength), RoundingMode.HALF_UP);
bigDecimal = bigDecimal.setScale(config.getInt("fractionalNumbers") + (3 - frontLength), RoundingMode.HALF_UP);
}
result = bigDecimal.toString();
} else {
@ -506,29 +524,29 @@ public class Utils {
bigDecimal = bigDecimal.setScale(config.getInt("fractionalNumbers"), RoundingMode.HALF_UP);
amount = bigDecimal.doubleValue();
result = bigDecimal.toString();
if(config.getBoolean("hideEmptyFractionalPart") && (amount%1.0) == 0.0 && result.contains(".")) {
if(config.getBoolean("hideEmptyFractionalPart") && (amount % 1.0) == 0.0 && result.contains(".")) {
result = result.substring(0, result.indexOf('.'));
}
}
}
result = result.replace(".", config.getString("decimalMark"));
return before+result+after;
return before + result + after;
}
/**
* Checks if the string is a correct time period
* Checks if the string is a correct time period.
* @param time String that has to be checked
* @return true if format is correct, false if not
*/
public static boolean checkTimeFormat(String time) {
// Check if the string is not empty and check the length
if(time == null || time.length() <= 1 || time.indexOf(' ') == -1 || time.indexOf(' ') >= (time.length()-1)) {
if(time == null || time.length() <= 1 || time.indexOf(' ') == -1 || time.indexOf(' ') >= (time.length() - 1)) {
return false;
}
// Check if the suffix is one of these values
String suffix = time.substring(time.indexOf(' ')+1, time.length());
String suffix = time.substring(time.indexOf(' ') + 1, time.length());
if(!identifiers.contains(suffix)) {
return false;
}
@ -539,7 +557,7 @@ public class Utils {
}
/**
* Methode to tranlate a duration string to a millisecond value
* Methode to tranlate a duration string to a millisecond value.
* @param duration The duration string
* @return The duration in milliseconds translated from the durationstring, or if it is invalid then 0
*/
@ -554,7 +572,7 @@ public class Utils {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(0);
String durationString = duration.substring(duration.indexOf(' ')+1, duration.length());
String durationString = duration.substring(duration.indexOf(' ') + 1, duration.length());
int durationInt = 0;
try {
durationInt = Integer.parseInt(duration.substring(0, duration.indexOf(' ')));
@ -571,7 +589,7 @@ public class Utils {
} else if(days.contains(durationString)) {
calendar.add(Calendar.DAY_OF_MONTH, durationInt);
} else if(weeks.contains(durationString)) {
calendar.add(Calendar.DAY_OF_MONTH, durationInt*7);
calendar.add(Calendar.DAY_OF_MONTH, durationInt * 7);
} else if(months.contains(durationString)) {
calendar.add(Calendar.MONTH, durationInt);
} else if(years.contains(durationString)) {
@ -583,7 +601,7 @@ public class Utils {
// LEGACY TIME INPUT CONVERSION
/**
* Get setting from config that could be only a number indicating seconds
* Get setting from config that could be only a number indicating seconds.
* or a string indicating a duration string
* @param path Path of the setting to read
* @return milliseconds that the setting indicates
@ -592,7 +610,7 @@ public class Utils {
if(config.isLong(path) || config.isInt(path)) {
long setting = config.getLong(path);
if(setting != -1) {
setting = setting*1000;
setting = setting * 1000;
}
return setting;
} else {
@ -601,8 +619,8 @@ public class Utils {
}
/**
* Get setting from config that could be only a number indicating minutes
* or a string indicating a duration string
* Get setting from config that could be only a number indicating minutes.
* or a string indicating a duration string.
* @param path Path of the setting to read
* @return milliseconds that the setting indicates
*/
@ -610,7 +628,7 @@ public class Utils {
if(config.isLong(path) || config.isInt(path)) {
long setting = config.getLong(path);
if(setting != -1) {
setting = setting*60*1000;
setting = setting * 60 * 1000;
}
return setting;
} else {
@ -619,7 +637,7 @@ public class Utils {
}
/**
* Parse a time setting that could be minutes or a duration string
* Parse a time setting that could be minutes or a duration string.
* @param input The string to parse
* @return milliseconds that the string indicates
*/
@ -628,7 +646,7 @@ public class Utils {
try {
number = Long.parseLong(input);
if(number != -1) {
number = number*60*1000;
number = number * 60 * 1000;
}
return number;
} catch(NumberFormatException e) {
@ -637,7 +655,7 @@ public class Utils {
}
/**
* Parse a time setting that could be seconds or a duration string
* Parse a time setting that could be seconds or a duration string.
* @param input The string to parse
* @return seconds that the string indicates
*/
@ -646,7 +664,7 @@ public class Utils {
try {
number = Long.parseLong(input);
if(number != -1) {
number = number*1000;
number = number * 1000;
}
return number;
} catch(NumberFormatException e) {
@ -655,7 +673,7 @@ public class Utils {
}
/**
* Check if an input is numeric
* Check if an input is numeric.
* @param input The input to check
* @return true if the input is numeric, otherwise false
*/
@ -670,7 +688,7 @@ public class Utils {
}
/**
* Check if a string is a double
* Check if a string is a double.
* @param input The input
* @return true if the input is a double, otherwise false
*/
@ -685,8 +703,8 @@ public class Utils {
}
/**
* Evaluate string input to a number
* Uses JavaScript for expressions
* Evaluate string input to a number.
* Uses JavaScript for expressions.
* @param input The input string
* @param region The region to apply replacements for and use for logging
* @return double evaluated from the input or a very high default in case of a script exception
@ -710,7 +728,7 @@ public class Utils {
try {
result = scriptEngine.eval(input);
} catch(ScriptException e) {
AreaShop.warn("Price of region", region.getName(), "is set with an invalid expression: '"+input+"', exception:", ExceptionUtils.getStackTrace(e));
AreaShop.warn("Price of region", region.getName(), "is set with an invalid expression: '" + input + "', exception:", ExceptionUtils.getStackTrace(e));
return 99999999999.0; // High fallback for safety
}
@ -718,7 +736,7 @@ public class Utils {
if(Utils.isDouble(result.toString())) {
return Double.parseDouble(result.toString());
} else {
AreaShop.warn("Price of region", region.getName(), "is set with the expression '"+input+"' that returns a result that is not a number:", result);
AreaShop.warn("Price of region", region.getName(), "is set with the expression '" + input + "' that returns a result that is not a number:", result);
return 99999999999.0; // High fallback for safety
}
}
@ -726,7 +744,7 @@ public class Utils {
// NAME <-> UUID CONVERSION
/**
* Conversion to name by uuid
* Conversion to name by uuid.
* @param uuid The uuid in string format
* @return the name of the player
*/
@ -744,7 +762,7 @@ public class Utils {
}
/**
* Conversion to name by uuid object
* Conversion to name by uuid object.
* @param uuid The uuid in string format
* @return the name of the player
*/
@ -761,12 +779,12 @@ public class Utils {
}
/**
* Conversion from name to uuid
* Conversion from name to uuid.
* @param name The name of the player
* @return The uuid of the player
*/
@SuppressWarnings("deprecation") // Fake deprecation by Bukkit to inform developers, method will stay
public static String toUUID(String name) {
public static String toUniqueId(String name) {
if(name == null) {
return null;
} else {

View File

@ -5,7 +5,7 @@ public class Value<T> {
private T value;
/**
* Create a container with a default value
* Create a container with a default value.
* @param value The value to set
*/
public Value(T value) {
@ -13,7 +13,7 @@ public class Value<T> {
}
/**
* Get the stored value
* Get the stored value.
* @return The stored value
*/
public T get() {
@ -21,7 +21,7 @@ public class Value<T> {
}
/**
* Set the value
* Set the value.
* @param value The new value
*/
public void set(T value) {

View File

@ -1,38 +1,38 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-interface</artifactId>
<packaging>jar</packaging>
<name>AreaShop Interface</name>
<version>AreaShopInterface</version>
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>
<artifactId>areashop-interface</artifactId>
<packaging>jar</packaging>
<name>AreaShop Interface</name>
<version>AreaShopInterface</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>LATEST</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>LATEST</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -8,8 +8,12 @@ import java.util.logging.Logger;
public interface AreaShopInterface {
void debugI(Object... message);
YamlConfiguration getConfig();
WorldGuardPlugin getWorldGuard();
WorldEditPlugin getWorldEdit();
Logger getLogger();
}

View File

@ -5,10 +5,16 @@ import org.bukkit.World;
public interface GeneralRegionInterface {
ProtectedRegion getRegion();
String getName();
World getWorld();
String getWorldName();
int getWidth();
int getDepth();
int getHeight();
}

View File

@ -4,13 +4,14 @@ import java.io.File;
public abstract class WorldEditInterface {
protected AreaShopInterface pluginInterface;
public WorldEditInterface(AreaShopInterface pluginInterface) {
this.pluginInterface = pluginInterface;
}
// Different way to restore blocks per implementation, newer ones support entities as well
public abstract boolean restoreRegionBlocks(File file, GeneralRegionInterface regionInterface);
// Different way to save blocks per implementation, newer ones support entities as well
public abstract boolean saveRegionBlocks(File file, GeneralRegionInterface regionInterface);
}

View File

@ -18,28 +18,28 @@ public abstract class WorldGuardInterface {
}
/**
* Parse an owner(s) string and set the players as owner of the WorldGuard region (set by UUID or name depending on implementation)
* Parse an owner(s) string and set the players as owner of the WorldGuard region (set by UUID or name depending on implementation).
* @param region The WorldGuard region to set the owners of
* @param input The owner(s) string to parse and set
*/
public abstract void setOwners(ProtectedRegion region, String input);
/**
* Parse a member(s) string and set the players as member of the WorldGuard region (set by UUID or name depending on implementation)
* Parse a member(s) string and set the players as member of the WorldGuard region (set by UUID or name depending on implementation).
* @param region The WorldGuard region to set the members of
* @param input The member(s) string to parse and set
*/
public abstract void setMembers(ProtectedRegion region, String input);
/**
* Get a set of ProtectedRegion's that are present on a certain location
* Get a set of ProtectedRegion's that are present on a certain location.
* @param location The location to check
* @return A set containing all regions present at that location
*/
public abstract Set<ProtectedRegion> getApplicableRegionsSet(Location location);
/**
* Check if a player is a member of the WorldGuard region
* Check if a player is a member of the WorldGuard region.
* @param region The region to check
* @param player The player to check
* @return true if the player is a member of the region, otherwise false
@ -47,7 +47,7 @@ public abstract class WorldGuardInterface {
public abstract boolean containsMember(ProtectedRegion region, UUID player);
/**
* Check if a player is an owner of the WorldGuard region
* Check if a player is an owner of the WorldGuard region.
* @param region The region to check
* @param player The player to check
* @return true if the player is an owner of the region, otherwise false
@ -55,14 +55,14 @@ public abstract class WorldGuardInterface {
public abstract boolean containsOwner(ProtectedRegion region, UUID player);
/**
* Get a flag from the name of a flag
* Get a flag from the name of a flag.
* @param flagName The name of the flag to get
* @return The specific flag type for the given name
*/
public abstract Flag<?> fuzzyMatchFlag(String flagName);
/**
* Convert string input to a region group flag value
* Convert string input to a region group flag value.
* @param flag The flag to parse the input for
* @param input The input
* @return The RegionGroup denoted by the input
@ -70,7 +70,7 @@ public abstract class WorldGuardInterface {
public abstract <V> V parseFlagInput(Flag<V> flag, String input) throws InvalidFlagFormat;
/**
* Convert string input to a region group flag value
* Convert string input to a region group flag value.
* @param flag The flag to parse the input for
* @param input The input
* @return The RegionGroup denoted by the input

View File

@ -1,44 +1,44 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-worldedit-5</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldEdit 5</name>
<version>WorldEdit-5</version>
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>
<artifactId>areashop-worldedit-5</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldEdit 5</name>
<version>WorldEdit-5</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.7-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>5.7-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -28,7 +28,7 @@ public class WorldEditHandler5 extends WorldEditInterface {
EditSession editSession = pluginInterface.getWorldEdit().getWorldEdit().getEditSessionFactory().getEditSession(new BukkitWorld(regionInterface.getWorld()), pluginInterface.getConfig().getInt("maximumBlocks"));
// Get the origin and size of the region
Vector origin = new Vector(regionInterface.getRegion().getMinimumPoint().getBlockX(), regionInterface.getRegion().getMinimumPoint().getBlockY(), regionInterface.getRegion().getMinimumPoint().getBlockZ());
editSession.enableQueue();
Exception otherException = null;
try {
@ -41,9 +41,9 @@ public class WorldEditHandler5 extends WorldEditInterface {
}
clipBoard.place(editSession, origin, false);
} catch(MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("Exeeded the block limit while restoring schematic of "+regionInterface.getName()+", limit in exception: "+e.getBlockLimit()+", limit passed by AreaShop: "+pluginInterface.getConfig().getInt("maximumBlocks"));
pluginInterface.getLogger().warning("Exeeded the block limit while restoring schematic of " + regionInterface.getName() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
result = false;
} catch(DataException|IOException e) {
} catch(DataException | IOException e) {
otherException = e;
}
if(otherException != null) {
@ -61,7 +61,7 @@ public class WorldEditHandler5 extends WorldEditInterface {
ProtectedRegion region = regionInterface.getRegion();
// Get the origin and size of the region
Vector origin = new Vector(region.getMinimumPoint().getBlockX(), region.getMinimumPoint().getBlockY(), region.getMinimumPoint().getBlockZ());
Vector size = (new Vector(region.getMaximumPoint().getBlockX(), region.getMaximumPoint().getBlockY(), region.getMaximumPoint().getBlockZ()).subtract(origin)).add(new Vector(1,1,1));
Vector size = (new Vector(region.getMaximumPoint().getBlockX(), region.getMaximumPoint().getBlockY(), region.getMaximumPoint().getBlockZ()).subtract(origin)).add(new Vector(1, 1, 1));
EditSession editSession = new EditSession(new BukkitWorld(regionInterface.getWorld()), pluginInterface.getConfig().getInt("maximumBlocks"));
// Save the schematic
editSession.enableQueue();
@ -70,7 +70,7 @@ public class WorldEditHandler5 extends WorldEditInterface {
Exception otherException = null;
try {
SchematicFormat.MCEDIT.save(clipboard, file);
} catch(DataException|IOException e) {
} catch(DataException | IOException e) {
otherException = e;
}
if(otherException != null) {
@ -83,5 +83,4 @@ public class WorldEditHandler5 extends WorldEditInterface {
}
}

View File

@ -1,44 +1,44 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-worldedit-6</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldEdit 6</name>
<version>WorldEdit-6</version>
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>
<artifactId>areashop-worldedit-6</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldEdit 6</name>
<version>WorldEdit-6</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -24,7 +24,12 @@ import me.wiefferink.areashop.interfaces.GeneralRegionInterface;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import org.apache.commons.lang.exception.ExceptionUtils;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WorldEditHandler6 extends WorldEditInterface {
@ -49,8 +54,7 @@ public class WorldEditHandler6 extends WorldEditInterface {
Vector origin = new Vector(region.getMinimumPoint().getBlockX(), region.getMinimumPoint().getBlockY(), region.getMinimumPoint().getBlockZ());
// Read the schematic and paste it into the world
Closer closer = Closer.create();
try {
try(Closer closer = Closer.create()) {
FileInputStream fis = closer.register(new FileInputStream(file));
BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
ClipboardReader reader = ClipboardFormat.SCHEMATIC.getReader(bis);
@ -73,18 +77,13 @@ public class WorldEditHandler6 extends WorldEditInterface {
.to(origin)
.build();
Operations.completeLegacy(operation);
} catch (MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("Exeeded the block limit while restoring schematic of "+regionInterface.getName()+", limit in exception: "+e.getBlockLimit()+", limit passed by AreaShop: "+pluginInterface.getConfig().getInt("maximumBlocks"));
} catch(MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("Exeeded the block limit while restoring schematic of " + regionInterface.getName() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
return false;
} catch (IOException e) {
} catch(IOException e) {
pluginInterface.getLogger().warning("An error occured while restoring schematic of " + regionInterface.getName() + ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
} finally {
try {
closer.close();
} catch (IOException ignored) {
}
}
editSession.flushQueue();
return true;
@ -109,24 +108,19 @@ public class WorldEditHandler6 extends WorldEditInterface {
try {
Operations.completeLegacy(copy);
} catch(MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("Exeeded the block limit while saving schematic of "+regionInterface.getName()+", limit in exception: "+e.getBlockLimit()+", limit passed by AreaShop: "+pluginInterface.getConfig().getInt("maximumBlocks"));
pluginInterface.getLogger().warning("Exeeded the block limit while saving schematic of " + regionInterface.getName() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
return false;
}
Closer closer = Closer.create();
try {
try(Closer closer = Closer.create()) {
FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
ClipboardWriter writer = closer.register(ClipboardFormat.SCHEMATIC.getWriter(bos));
writer.write(clipboard, world.getWorldData());
} catch (IOException e) {
} catch(IOException e) {
pluginInterface.getLogger().warning("An error occured while saving schematic of " + regionInterface.getName() + ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
} finally {
try {
closer.close();
} catch (IOException ignored) {
}
}
return true;
}

View File

@ -1,37 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-worldguard-5</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldGuard 5</name>
<version>WorldGuard-5</version>
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>
<artifactId>areashop-worldguard-5</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldGuard 5</name>
<version>WorldGuard-5</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.9.1-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>5.9.1-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -3,7 +3,11 @@ package me.wiefferink.areashop.handlers;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
@ -21,6 +25,7 @@ public class WorldGuardHandler5 extends WorldGuardInterface {
super(pluginInterface);
}
@Override
public void setOwners(ProtectedRegion region, String input) {
// Split the string and parse all values
String[] names = input.split(", ");
@ -36,9 +41,9 @@ public class WorldGuardHandler5 extends WorldGuardInterface {
} else if(owner.startsWith("n:")) {
if(owner.length() > 2) {
owners.addPlayer(owner.substring(2));
}
}
} else {
UUID uuid;
UUID uuid;
try {
uuid = UUID.fromString(owner);
} catch(IllegalArgumentException e) {
@ -58,6 +63,7 @@ public class WorldGuardHandler5 extends WorldGuardInterface {
//System.out.println(" Flag " + flagName + " set: " + owners.toUserFriendlyString());
}
@Override
public void setMembers(ProtectedRegion region, String input) {
// Split the string and parse all values
String[] names = input.split(", ");
@ -73,9 +79,9 @@ public class WorldGuardHandler5 extends WorldGuardInterface {
} else if(member.startsWith("n:")) {
if(member.length() > 2) {
members.addPlayer(member.substring(2));
}
}
} else {
UUID uuid;
UUID uuid;
try {
uuid = UUID.fromString(member);
} catch(IllegalArgumentException e) {

View File

@ -1,37 +1,37 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-worldguard-6</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldGuard 6</name>
<version>WorldGuard-6</version>
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>
<artifactId>areashop-worldguard-6</artifactId>
<packaging>jar</packaging>
<name>AreaShop WorldGuard 6</name>
<version>WorldGuard-6</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>parent</version>
</parent>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8-R0.1-SNAPSHOT</version>
<type>jar</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>AreaShopInterface</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldguard</artifactId>
<version>6.0.0-SNAPSHOT</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
</dependencies>
</project>

View File

@ -3,7 +3,11 @@ package me.wiefferink.areashop.handlers;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.interfaces.WorldGuardInterface;
@ -19,6 +23,7 @@ public class WorldGuardHandler6 extends WorldGuardInterface {
super(pluginInterface);
}
@Override
public void setOwners(ProtectedRegion region, String input) {
// Split the string and parse all values
String[] names = input.split(", ");
@ -34,9 +39,9 @@ public class WorldGuardHandler6 extends WorldGuardInterface {
} else if(owner.startsWith("n:")) {
if(owner.length() > 2) {
owners.addPlayer(owner.substring(2));
}
} else {
UUID uuid;
}
} else {
UUID uuid;
try {
uuid = UUID.fromString(owner);
} catch(IllegalArgumentException e) {
@ -54,6 +59,7 @@ public class WorldGuardHandler6 extends WorldGuardInterface {
//System.out.println(" Flag " + flagName + " set: " + owners.toUserFriendlyString());
}
@Override
public void setMembers(ProtectedRegion region, String input) {
// Split the string and parse all values
String[] names = input.split(", ");
@ -69,9 +75,9 @@ public class WorldGuardHandler6 extends WorldGuardInterface {
} else if(member.startsWith("n:")) {
if(member.length() > 2) {
members.addPlayer(member.substring(2));
}
}
} else {
UUID uuid;
UUID uuid;
try {
uuid = UUID.fromString(member);
} catch(IllegalArgumentException e) {
@ -88,7 +94,7 @@ public class WorldGuardHandler6 extends WorldGuardInterface {
region.setMembers(members);
//System.out.println(" Flag " + flagName + " set: " + members.toUserFriendlyString());
}
@Override
public Set<ProtectedRegion> getApplicableRegionsSet(Location location) {
Set<ProtectedRegion> result = new HashSet<>();

View File

@ -1,7 +1,12 @@
package me.wiefferink.areashop.handlers;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.flags.*;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
public class WorldGuardHandler6_1_3 extends WorldGuardHandler6 {

View File

@ -0,0 +1,9 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.0//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_0.dtd">
<suppressions>
<suppress files="WorldGuardHandler6_1_3.java" checks="TypeName" />
</suppressions>

204
config/checkstyle.xml Normal file
View File

@ -0,0 +1,204 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
Based on the Google Java Style Guide: https://google.github.io/styleguide/javaguide.html
-->
<module name = "Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="TreeWalker">
<!-- Tab indentation -->
<module name="RegexpSinglelineJava">
<property name="format" value="^\t* +\t*\S"/>
<property name="message" value="Line has leading space characters; indentation should be performed with tabs only."/>
<property name="ignoreComments" value="true"/>
</module>
<property name="tabWidth" value="4"/>
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="maxLineLength" value="100"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<property name="tokens" value="ASSIGN, ARRAY_INIT, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAMBDA, LAND, LCURLY, LE, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_RETURN, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="Indentation">
<property name="basicOffset" value="4"/>
<property name="braceAdjustment" value="0"/>
<property name="caseIndent" value="4"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
</module>
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
<module name="JavadocTagContinuationIndentation"/>
<!-- Add dot to javadoc: search: "(\t*\* [^@\n\.]+)\n", replace: "$1.\n" -->
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments" value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
<module name="JavadocParagraph"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<module name="JavadocMethod">
<property name="scope" value="protected"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc">
<property name="ignoreInlineTags" value="false"/>
</module>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation"/>
<module name="MissingOverride"/>
</module>
</module>

35
pom.xml
View File

@ -48,4 +48,39 @@
<module>AreaShop</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.17</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>7.6</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>config/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle-suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>config/checkstyle.suppressions.file</suppressionsFileExpression>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<violationSeverity>error</violationSeverity>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>