Refactoring based on SonarLint and Intellij IDEA inspections

This commit is contained in:
Thijs Wiefferink 2019-01-26 21:23:49 +01:00
parent b7124e8cdd
commit e0bad7397c
32 changed files with 224 additions and 236 deletions

View File

@ -142,6 +142,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
/** /**
* Called on start or reload of the server. * Called on start or reload of the server.
*/ */
@Override
public void onEnable() { public void onEnable() {
AreaShop.instance = this; AreaShop.instance = this;
Do.init(this); Do.init(this);
@ -201,10 +202,10 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
if(rawWgVersion.contains("-SNAPSHOT;")) { if(rawWgVersion.contains("-SNAPSHOT;")) {
String buildNumber = rawWgVersion.substring(rawWgVersion.indexOf("-SNAPSHOT;") + 10); String buildNumber = rawWgVersion.substring(rawWgVersion.indexOf("-SNAPSHOT;") + 10);
if(buildNumber.contains("-")) { if(buildNumber.contains("-")) {
buildNumber = buildNumber.substring(0, buildNumber.indexOf("-")); buildNumber = buildNumber.substring(0, buildNumber.indexOf('-'));
try { if (Utils.isNumeric(buildNumber)) {
build = Integer.parseInt(buildNumber); build = Integer.parseInt(buildNumber);
} catch(NumberFormatException e) { } else {
warn("Could not correctly parse the build of WorldGuard, raw version: " + rawWgVersion + ", buildNumber: " + buildNumber); warn("Could not correctly parse the build of WorldGuard, raw version: " + rawWgVersion + ", buildNumber: " + buildNumber);
} }
} }
@ -326,7 +327,8 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
// Load all data from files and check versions // Load all data from files and check versions
fileManager = new FileManager(); fileManager = new FileManager();
managers.add(fileManager); managers.add(fileManager);
error = error | !fileManager.loadFiles(false); boolean loadFilesResult = fileManager.loadFiles(false);
error = error || !loadFilesResult;
// Print loaded version of WG and WE in debug // Print loaded version of WG and WE in debug
if(wgVersion != null) { if(wgVersion != null) {
@ -373,7 +375,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
"AreaShop" "AreaShop"
).withVersionComparator((latestVersion, currentVersion) -> ).withVersionComparator((latestVersion, currentVersion) ->
!cleanVersion(latestVersion).equals(cleanVersion(currentVersion)) !cleanVersion(latestVersion).equals(cleanVersion(currentVersion))
).checkUpdate((result) -> { ).checkUpdate(result -> {
AreaShop.debug("Update check result:", result); AreaShop.debug("Update check result:", result);
if(!result.hasUpdate()) { if(!result.hasUpdate()) {
return; return;
@ -422,6 +424,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
/** /**
* Called on shutdown or reload of the server. * Called on shutdown or reload of the server.
*/ */
@Override
public void onDisable() { public void onDisable() {
Bukkit.getServer().getScheduler().cancelTasks(this); Bukkit.getServer().getScheduler().cancelTasks(this);
@ -500,6 +503,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* Function to get the WorldGuard plugin. * Function to get the WorldGuard plugin.
* @return WorldGuardPlugin * @return WorldGuardPlugin
*/ */
@Override
public WorldGuardPlugin getWorldGuard() { public WorldGuardPlugin getWorldGuard() {
return worldGuard; return worldGuard;
} }
@ -525,6 +529,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* Function to get the WorldEdit plugin. * Function to get the WorldEdit plugin.
* @return WorldEditPlugin * @return WorldEditPlugin
*/ */
@Override
public WorldEditPlugin getWorldEdit() { public WorldEditPlugin getWorldEdit() {
return worldEdit; return worldEdit;
} }
@ -771,6 +776,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* Non-static debug to use as implementation of the interface. * Non-static debug to use as implementation of the interface.
* @param message Object parts of the message that should be logged, toString() will be used * @param message Object parts of the message that should be logged, toString() will be used
*/ */
@Override
public void debugI(Object... message) { public void debugI(Object... message) {
AreaShop.debug(StringUtils.join(message, " ")); AreaShop.debug(StringUtils.join(message, " "));
} }

View File

@ -57,7 +57,7 @@ public class AddCommand extends CommandAreaShop {
return; return;
} }
if(args.length < 2 || args[1] == null || (!"rent".equals(args[1].toLowerCase()) && !"buy".equals(args[1].toLowerCase()))) { if(args.length < 2 || args[1] == null || (!"rent".equalsIgnoreCase(args[1]) && !"buy".equalsIgnoreCase(args[1]))) {
plugin.message(sender, "add-help"); plugin.message(sender, "add-help");
return; return;
} }
@ -79,7 +79,7 @@ public class AddCommand extends CommandAreaShop {
} }
world = selection.getWorld(); world = selection.getWorld();
regions = Utils.getWorldEditRegionsInSelection(selection).stream().collect(Collectors.toMap(ProtectedRegion::getId, region -> region)); regions = Utils.getWorldEditRegionsInSelection(selection).stream().collect(Collectors.toMap(ProtectedRegion::getId, region -> region));
if(regions.size() == 0) { if(regions.isEmpty()) {
plugin.message(player, "cmd-noWERegionsFound"); plugin.message(player, "cmd-noWERegionsFound");
return; return;
} }
@ -113,7 +113,7 @@ public class AddCommand extends CommandAreaShop {
} }
regions.put(args[2], region); regions.put(args[2], region);
} }
final boolean isRent = "rent".equals(args[1].toLowerCase()); final boolean isRent = "rent".equalsIgnoreCase(args[1]);
final Player finalPlayer = player; final Player finalPlayer = player;
AreaShop.debug("Starting add task with " + regions.size() + " regions"); AreaShop.debug("Starting add task with " + regions.size() + " regions");

View File

@ -90,8 +90,8 @@ public abstract class CommandAreaShop {
} }
private class CommandTime { private class CommandTime {
public String command; public final String command;
public long time; public final long time;
CommandTime(String command, long time) { CommandTime(String command, long time) {
this.command = command; this.command = command;

View File

@ -50,7 +50,7 @@ public class DelCommand extends CommandAreaShop {
return; return;
} }
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection); List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions == null || regions.size() == 0) { if(regions == null || regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound"); plugin.message(player, "cmd-noRegionsFound");
return; return;
} }
@ -76,10 +76,10 @@ public class DelCommand extends CommandAreaShop {
} }
} }
// send messages // send messages
if(namesSuccess.size() != 0) { if(!namesSuccess.isEmpty()) {
plugin.message(sender, "del-success", Utils.createCommaSeparatedList(namesSuccess)); plugin.message(sender, "del-success", Utils.createCommaSeparatedList(namesSuccess));
} }
if(namesFailed.size() != 0) { if(!namesFailed.isEmpty()) {
plugin.message(sender, "del-failed", Utils.combinedMessage(namesFailed, "region")); plugin.message(sender, "del-failed", Utils.combinedMessage(namesFailed, "region"));
} }
} else { } else {

View File

@ -53,7 +53,7 @@ public class GroupaddCommand extends CommandAreaShop {
return; return;
} }
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection); List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) { if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound"); plugin.message(player, "cmd-noRegionsFound");
return; return;
} }
@ -66,10 +66,10 @@ public class GroupaddCommand extends CommandAreaShop {
regionsFailed.add(region); regionsFailed.add(region);
} }
} }
if(regionsSuccess.size() != 0) { if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region")); plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
} }
if(regionsFailed.size() != 0) { if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region")); plugin.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
} }
// Update all regions, this does it in a task, updating them without lag // Update all regions, this does it in a task, updating them without lag

View File

@ -54,7 +54,7 @@ public class GroupdelCommand extends CommandAreaShop {
return; return;
} }
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection); List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) { if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound"); plugin.message(player, "cmd-noRegionsFound");
return; return;
} }
@ -67,10 +67,10 @@ public class GroupdelCommand extends CommandAreaShop {
regionsFailed.add(region); regionsFailed.add(region);
} }
} }
if(regionsSuccess.size() != 0) { if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region")); plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
} }
if(regionsFailed.size() != 0) { if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region")); plugin.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
} }
// Update all regions, this does it in a task, updating them without lag // Update all regions, this does it in a task, updating them without lag

View File

@ -40,7 +40,7 @@ public class GroupinfoCommand extends CommandAreaShop {
return; return;
} }
Set<String> members = group.getMembers(); Set<String> members = group.getMembers();
if(members.size() == 0) { if(members.isEmpty()) {
plugin.message(sender, "groupinfo-noMembers", group.getName()); plugin.message(sender, "groupinfo-noMembers", group.getName());
} else { } else {
plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members)); plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members));

View File

@ -28,7 +28,7 @@ public class GrouplistCommand extends CommandAreaShop {
return; return;
} }
List<String> groups = plugin.getFileManager().getGroupNames(); List<String> groups = plugin.getFileManager().getGroupNames();
if(groups.size() == 0) { if(groups.isEmpty()) {
plugin.message(sender, "grouplist-noGroups"); plugin.message(sender, "grouplist-noGroups");
} else { } else {
plugin.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups)); plugin.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups));

View File

@ -27,11 +27,11 @@ public class ImportCommand extends CommandAreaShop {
return null; return null;
} }
// TODO // TODO:
// - Landlord? // - Landlord?
// - Friends // - Friends
// - Region flags? // - Region flags?
// - Settings from the 'permissions' section in RegionForSale/config.yml? // - Settings from the 'permissions' section in RegionForSale/config.yml?
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
@ -54,7 +54,7 @@ public class ImportCommand extends CommandAreaShop {
return; return;
} }
ImportJob importJob = new ImportJob(sender); new ImportJob(sender);
} }
@Override @Override

View File

@ -330,7 +330,7 @@ public class ImportJob {
String buyPrice = from.getString("economic-settings.cost-per-unit.buy"); String buyPrice = from.getString("economic-settings.cost-per-unit.buy");
String sellPrice = from.getString("economic-settings.cost-per-unit.selling-price"); String sellPrice = from.getString("economic-settings.cost-per-unit.selling-price");
// TODO: There is no easy way to import this, setup eventCommandsProfile? // TODO: There is no easy way to import this, setup eventCommandsProfile?
String taxes = from.getString("economic-settings.cost-per-unit.taxes"); // String taxes = from.getString("economic-settings.cost-per-unit.taxes");
// Determine unit and add that to the price // Determine unit and add that to the price
String unitSuffix = ""; String unitSuffix = "";
@ -411,8 +411,8 @@ public class ImportJob {
} }
private static class TimeUnit { private static class TimeUnit {
public long minutes; public final long minutes;
public String identifier; public final String identifier;
TimeUnit(long minutes, String identifier) { TimeUnit(long minutes, String identifier) {
this.minutes = minutes; this.minutes = minutes;

View File

@ -113,9 +113,9 @@ public class InfoCommand extends CommandAreaShop {
} }
// Page status // Page status
if(totalPages > 1) { if(totalPages > 1) {
String pageString = "" + page; StringBuilder pageString = new StringBuilder("" + page);
for(int i = pageString.length(); i < (totalPages + "").length(); i++) { for(int i = pageString.length(); i < (totalPages + "").length(); i++) {
pageString = "0" + pageString; pageString.insert(0, "0");
} }
footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages)); footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages));
if(page < totalPages) { if(page < totalPages) {

View File

@ -19,9 +19,7 @@ public class MessageCommand extends CommandAreaShop {
@Override @Override
public String getHelp(CommandSender target) { public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.message")) { // Internal command, no need to show in the help list
return null; // Internal command, no need to show in the help list
}
return null; return null;
} }

View File

@ -157,33 +157,16 @@ public class StackCommand extends CommandAreaShop {
current++; current++;
if(current < amount) { if(current < amount) {
// Create the region name // Create the region name
String counterName = counter + ""; String regionName = countToName(nameTemplate, counter);
int minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName = "0" + counterName;
}
String regionName;
if(nameTemplate.contains("#")) {
regionName = nameTemplate.replace("#", counterName);
} else {
regionName = nameTemplate + counterName;
}
while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) { while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) {
counter++; counter++;
counterName = counter + ""; regionName = countToName(nameTemplate, counter);
minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName = "0" + counterName;
}
if(nameTemplate.contains("#")) {
regionName = nameTemplate.replace("#", counterName);
} else {
regionName = nameTemplate + counterName;
}
} }
// Add the region to WorldGuard (at startposition shifted by the number of this region times the blocks it should shift) // Add the region to WorldGuard (at startposition shifted by the number of this region times the blocks it should shift)
Vector minimum = minimumVector.clone().add(finalShift.clone().multiply(current)); Vector minimum = minimumVector.clone().add(finalShift.clone().multiply(current));
Vector maximum = maximumVector.clone().add(finalShift.clone().multiply(current)); Vector maximum = maximumVector.clone().add(finalShift.clone().multiply(current));
// Check for out of bounds // Check for out of bounds
if(minimum.getBlockY() < 0) { if(minimum.getBlockY() < 0) {
tooLow++; tooLow++;
@ -194,6 +177,7 @@ public class StackCommand extends CommandAreaShop {
} }
ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum); ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum);
manager.addRegion(region); manager.addRegion(region);
// Add the region to AreaShop // Add the region to AreaShop
if(rentRegions) { if(rentRegions) {
RentRegion rent = new RentRegion(regionName, selection.getWorld()); RentRegion rent = new RentRegion(regionName, selection.getWorld());
@ -236,6 +220,26 @@ public class StackCommand extends CommandAreaShop {
}.runTaskTimer(plugin, 1, 1); }.runTaskTimer(plugin, 1, 1);
} }
/**
* Build a name from a count, with the right length.
* @param template Template to put the name in (# to put the count there, otherwise count is appended)
* @param count Number to use
* @return name with prepended 0's
*/
private String countToName(String template, int count) {
StringBuilder counterName = new StringBuilder().append(count);
int minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName.insert(0, "0");
}
if(template.contains("#")) {
return template.replace("#", counterName);
} else {
return template + counterName;
}
}
@Override @Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) { public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();

View File

@ -59,12 +59,13 @@ public class TeleportCommand extends CommandAreaShop {
plugin.message(player, "teleport-noRentOrBuy", args[1]); plugin.message(player, "teleport-noRentOrBuy", args[1]);
return; return;
} }
if(args.length >= 3 && (args[2].equalsIgnoreCase("sign") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) {
region.getTeleportFeature().teleportPlayer(player, true);
} else {
region.getTeleportFeature().teleportPlayer(player, false);
}
boolean toSign = args.length >= 3 && (
args[2].equalsIgnoreCase("sign")
|| args[2].equalsIgnoreCase("yes")
|| args[2].equalsIgnoreCase("true")
);
region.getTeleportFeature().teleportPlayer(player, toSign);
} }
@Override @Override

View File

@ -16,10 +16,6 @@ public class RegionEvent<T> extends Event {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() {
return handlers;
}
/** /**
* Get the region of this event. * Get the region of this event.
* @return The region the event is about * @return The region the event is about

View File

@ -147,7 +147,7 @@ public class TeleportFeature extends RegionFeature {
int maxTries = plugin.getConfig().getInt("maximumTries"); int maxTries = plugin.getConfig().getInt("maximumTries");
// Tracking of which sides to continue the search // Tracking of which sides to continue the search
boolean done = isSafe(safeLocation) && (blocksInRegion || !insideRegion); boolean done = isSafe(safeLocation);
boolean northDone = false, eastDone = false, southDone = false, westDone = false, topDone = false, bottomDone = false; boolean northDone = false, eastDone = false, southDone = false, westDone = false, topDone = false, bottomDone = false;
boolean continueThisDirection; boolean continueThisDirection;

View File

@ -42,7 +42,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
// Region flags for all states // Region flags for all states
ConfigurationSection allFlags = flagProfileSection.getConfigurationSection("ALL"); ConfigurationSection allFlags = flagProfileSection.getConfigurationSection("ALL");
if(allFlags != null) { if(allFlags != null) {
result = result && updateRegionFlags(region, allFlags); result = updateRegionFlags(region, allFlags);
} }
// Region flags for the current state // Region flags for the current state
@ -52,9 +52,8 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
if(stateFlags == null && region.getState() == GeneralRegion.RegionState.RESELL) { if(stateFlags == null && region.getState() == GeneralRegion.RegionState.RESELL) {
stateFlags = flagProfileSection.getConfigurationSection("resale"); stateFlags = flagProfileSection.getConfigurationSection("resale");
} }
if(stateFlags != null) { if(stateFlags != null) {
result = result && updateRegionFlags(region, stateFlags); result &= updateRegionFlags(region, stateFlags);
} }
return result; return result;

View File

@ -194,7 +194,7 @@ public class SignsFeature extends RegionFeature {
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld()); RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location // If the secondLine does not contain a name try to find the region by location
if(secondLine == null || secondLine.length() == 0) { if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation()); Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) { if(regions != null) {
boolean first = true; boolean first = true;
@ -224,10 +224,10 @@ public class SignsFeature extends RegionFeature {
} }
} }
boolean priceSet = fourthLine != null && fourthLine.length() != 0; boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && thirdLine.length() != 0; boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct // check if all the lines are correct
if(secondLine == null || secondLine.length() == 0) { if(secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion"); plugin.message(player, "setup-noRegion");
return; return;
} }
@ -246,7 +246,7 @@ public class SignsFeature extends RegionFeature {
plugin.message(player, "setup-alreadyOtherWorld"); plugin.message(player, "setup-alreadyOtherWorld");
} else if(addResult == FileManager.AddResult.NOPERMISSION) { } else if(addResult == FileManager.AddResult.NOPERMISSION) {
plugin.message(player, "setup-noPermission", secondLine); plugin.message(player, "setup-noPermission", secondLine);
} else if(thirdLine != null && thirdLine.length() != 0 && !Utils.checkTimeFormat(thirdLine)) { } else if(thirdLine != null && !thirdLine.isEmpty() && !Utils.checkTimeFormat(thirdLine)) {
plugin.message(player, "setup-wrongDuration"); plugin.message(player, "setup-wrongDuration");
} else { } else {
double price = 0.0; double price = 0.0;
@ -306,7 +306,7 @@ public class SignsFeature extends RegionFeature {
RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld()); RegionManager regionManager = plugin.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location // If the secondLine does not contain a name try to find the region by location
if(secondLine == null || secondLine.length() == 0) { if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation()); Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) { if(regions != null) {
boolean first = true; boolean first = true;
@ -336,9 +336,9 @@ public class SignsFeature extends RegionFeature {
} }
} }
boolean priceSet = thirdLine != null && thirdLine.length() != 0; boolean priceSet = thirdLine != null && !thirdLine.isEmpty();
// Check if all the lines are correct // Check if all the lines are correct
if(secondLine == null || secondLine.length() == 0) { if(secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion"); plugin.message(player, "setup-noRegion");
return; return;
} }
@ -408,7 +408,7 @@ public class SignsFeature extends RegionFeature {
String thirdLine = event.getLine(2); String thirdLine = event.getLine(2);
GeneralRegion region; GeneralRegion region;
if(secondLine != null && secondLine.length() != 0) { if(secondLine != null && !secondLine.isEmpty()) {
// Get region by secondLine of the sign // Get region by secondLine of the sign
region = plugin.getFileManager().getRegion(secondLine); region = plugin.getFileManager().getRegion(secondLine);
if(region == null) { if(region == null) {
@ -428,7 +428,7 @@ public class SignsFeature extends RegionFeature {
region = regions.get(0); region = regions.get(0);
} }
org.bukkit.material.Sign sign = (org.bukkit.material.Sign)event.getBlock().getState().getData(); org.bukkit.material.Sign sign = (org.bukkit.material.Sign)event.getBlock().getState().getData();
if(thirdLine == null || thirdLine.length() == 0) { if(thirdLine == null || thirdLine.isEmpty()) {
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null); region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null);
plugin.message(player, "addsign-success", region); plugin.message(player, "addsign-success", region);
} else { } else {
@ -516,7 +516,7 @@ public class SignsFeature extends RegionFeature {
public boolean update() { public boolean update() {
boolean result = true; boolean result = true;
for(RegionSign sign : signs.values()) { for(RegionSign sign : signs.values()) {
result = result & sign.update(); result &= sign.update();
} }
return result; return result;
} }
@ -528,7 +528,7 @@ public class SignsFeature extends RegionFeature {
public boolean needsPeriodicUpdate() { public boolean needsPeriodicUpdate() {
boolean result = false; boolean result = false;
for(RegionSign sign : signs.values()) { for(RegionSign sign : signs.values()) {
result = result | sign.needsPeriodicUpdate(); result |= sign.needsPeriodicUpdate();
} }
return result; return result;
} }
@ -577,7 +577,7 @@ public class SignsFeature extends RegionFeature {
getRegion().setSetting(signPath + "location", Utils.locationToConfig(location)); getRegion().setSetting(signPath + "location", Utils.locationToConfig(location));
getRegion().setSetting(signPath + "facing", facing != null ? facing.name() : null); getRegion().setSetting(signPath + "facing", facing != null ? facing.name() : null);
getRegion().setSetting(signPath + "signType", signType != null ? signType.name() : null); getRegion().setSetting(signPath + "signType", signType != null ? signType.name() : null);
if(profile != null && profile.length() != 0) { if(profile != null && !profile.isEmpty()) {
getRegion().setSetting(signPath + "profile", profile); getRegion().setSetting(signPath + "profile", profile);
} }
// Add to the map // Add to the map
@ -588,28 +588,4 @@ public class SignsFeature extends RegionFeature {
.add(sign); .add(sign);
} }
/**
* 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
*/
public boolean isSignOfRegion(Location location) {
Set<String> signs;
if(getRegion().getConfig().getConfigurationSection("general.signs") == null) {
return false;
}
signs = getRegion().getConfig().getConfigurationSection("general.signs").getKeys(false);
for(String sign : signs) {
Location signLocation = Utils.configToLocation(getRegion().getConfig().getConfigurationSection("general.signs." + sign + ".location"));
if(signLocation != null
&& signLocation.getWorld().equals(location.getWorld())
&& signLocation.getBlockX() == location.getBlockX()
&& signLocation.getBlockY() == location.getBlockY()
&& signLocation.getBlockZ() == location.getBlockZ()) {
return true;
}
}
return false;
}
} }

View File

@ -95,7 +95,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
* Get the list with AreaShop commands. * Get the list with AreaShop commands.
* @return The list with AreaShop commands * @return The list with AreaShop commands
*/ */
public ArrayList<CommandAreaShop> getCommands() { public List<CommandAreaShop> getCommands() {
return commands; return commands;
} }
@ -114,7 +114,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
plugin.message(target, "help-alias"); plugin.message(target, "help-alias");
for(CommandAreaShop command : commands) { for(CommandAreaShop command : commands) {
String help = command.getHelp(target); String help = command.getHelp(target);
if(help != null && help.length() != 0) { if(help != null && !help.isEmpty()) {
messages.add(help); messages.add(help);
} }
} }
@ -130,11 +130,13 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
plugin.message(sender, "general-notReady"); plugin.message(sender, "general-notReady");
return true; return true;
} }
// Redirect `/as info player <player>` to `/as me <player>` // Redirect `/as info player <player>` to `/as me <player>`
if(args.length == 3 && "info".equals(args[0]) && "player".equals(args[1])) { if(args.length == 3 && "info".equals(args[0]) && "player".equals(args[1])) {
args[0] = "me"; args[0] = "me";
args[1] = args[2]; args[1] = args[2];
} }
// Execute command // Execute command
boolean executed = false; boolean executed = false;
for(int i = 0; i < commands.size() && !executed; i++) { for(int i = 0; i < commands.size() && !executed; i++) {
@ -143,16 +145,21 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
executed = true; executed = true;
} }
} }
if(!executed && args.length == 0) {
this.showHelp(sender); // Show help
} else if(!executed && args.length > 0) { if (!executed) {
// Indicate that the '/as updaterents' and '/as updatebuys' commands are removed if (args.length == 0) {
if("updaterents".equalsIgnoreCase(args[0]) || "updatebuys".equalsIgnoreCase(args[0])) { this.showHelp(sender);
plugin.message(sender, "reload-updateCommandChanged");
} else { } else {
plugin.message(sender, "cmd-notValid"); // Indicate that the '/as updaterents' and '/as updatebuys' commands are removed
if("updaterents".equalsIgnoreCase(args[0]) || "updatebuys".equalsIgnoreCase(args[0])) {
plugin.message(sender, "reload-updateCommandChanged");
} else {
plugin.message(sender, "cmd-notValid");
}
} }
} }
return true; return true;
} }
@ -181,7 +188,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
} }
} }
// Filter and sort the results // Filter and sort the results
if(result.size() > 0) { if(!result.isEmpty()) {
SortedSet<String> set = new TreeSet<>(); SortedSet<String> set = new TreeSet<>();
for(String suggestion : result) { for(String suggestion : result) {
if(suggestion.toLowerCase().startsWith(toCompletePrefix)) { if(suggestion.toLowerCase().startsWith(toCompletePrefix)) {

View File

@ -40,13 +40,11 @@ public class FeatureManager extends Manager {
for(Class<? extends RegionFeature> clazz : featureClasses) { for(Class<? extends RegionFeature> clazz : featureClasses) {
try { try {
Constructor<? extends RegionFeature> constructor = clazz.getConstructor(); Constructor<? extends RegionFeature> constructor = clazz.getConstructor();
try { RegionFeature feature = constructor.newInstance();
RegionFeature feature = constructor.newInstance(); feature.listen();
feature.listen(); globalFeatures.add(feature);
globalFeatures.add(feature); } catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { AreaShop.error("Failed to instantiate global feature:", clazz, e);
AreaShop.error("Failed to instantiate global feature:", clazz, e);
}
} catch(NoSuchMethodException e) { } catch(NoSuchMethodException e) {
// Feature does not have a global part // Feature does not have a global part
} }

View File

@ -421,8 +421,8 @@ public class FileManager extends Manager {
AreaShop.debug("Removed sign at: " + sign.toString()); AreaShop.debug("Removed sign at: " + sign.toString());
} }
} }
RegionGroup[] groups = getGroups().toArray(new RegionGroup[getGroups().size()]); RegionGroup[] regionGroups = getGroups().toArray(new RegionGroup[0]);
for(RegionGroup group : groups) { for(RegionGroup group : regionGroups) {
group.removeMember(rent); group.removeMember(rent);
} }
rent.resetRegionFlags(); rent.resetRegionFlags();
@ -738,16 +738,14 @@ public class FileManager extends Manager {
File file = new File(versionPath); File file = new File(versionPath);
if(file.exists()) { if(file.exists()) {
// Load versions from the file // Load versions from the file
try { try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(versionPath))) {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(versionPath)); versions = (HashMap<String, Integer>) input.readObject();
versions = (HashMap<String, Integer>)input.readObject();
input.close();
} catch(IOException | ClassNotFoundException | ClassCastException e) { } catch(IOException | ClassNotFoundException | ClassCastException e) {
AreaShop.warn("Something went wrong reading file: " + versionPath); AreaShop.warn("Something went wrong reading file: " + versionPath);
versions = null; versions = null;
} }
} }
if(versions == null || versions.size() == 0) { if(versions == null || versions.isEmpty()) {
versions = new HashMap<>(); versions = new HashMap<>();
versions.put(AreaShop.versionFiles, 0); versions.put(AreaShop.versionFiles, 0);
this.saveVersions(); this.saveVersions();
@ -761,10 +759,8 @@ public class FileManager extends Manager {
if(!(new File(versionPath).exists())) { if(!(new File(versionPath).exists())) {
AreaShop.debug("versions file created, this should happen only after installing or upgrading the plugin"); AreaShop.debug("versions file created, this should happen only after installing or upgrading the plugin");
} }
try { try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(versionPath))) {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(versionPath));
output.writeObject(versions); output.writeObject(versions);
output.close();
} catch(IOException e) { } catch(IOException e) {
AreaShop.warn("File could not be saved: " + versionPath); AreaShop.warn("File could not be saved: " + versionPath);
} }
@ -820,8 +816,6 @@ public class FileManager extends Manager {
while((read = input.read(bytes)) != -1) { while((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read); output.write(bytes, 0, read);
} }
input.close();
output.close();
AreaShop.info("File with default region settings has been saved, should only happen on first startup"); AreaShop.info("File with default region settings has been saved, should only happen on first startup");
} catch(IOException e) { } catch(IOException e) {
AreaShop.warn("Something went wrong saving the default region settings: " + defaultFile.getAbsolutePath()); AreaShop.warn("Something went wrong saving the default region settings: " + defaultFile.getAbsolutePath());
@ -833,7 +827,7 @@ public class FileManager extends Manager {
InputStreamReader normal = new InputStreamReader(plugin.getResource(AreaShop.defaultFile), Charsets.UTF_8) InputStreamReader normal = new InputStreamReader(plugin.getResource(AreaShop.defaultFile), Charsets.UTF_8)
) { ) {
defaultConfig = YamlConfiguration.loadConfiguration(custom); defaultConfig = YamlConfiguration.loadConfiguration(custom);
if(defaultConfig.getKeys(false).size() == 0) { if(defaultConfig.getKeys(false).isEmpty()) {
AreaShop.warn("File 'default.yml' is empty, check for errors in the log."); AreaShop.warn("File 'default.yml' is empty, check for errors in the log.");
result = false; result = false;
} }
@ -874,7 +868,7 @@ public class FileManager extends Manager {
InputStreamReader hidden = new InputStreamReader(plugin.getResource(AreaShop.configFileHidden), Charsets.UTF_8) InputStreamReader hidden = new InputStreamReader(plugin.getResource(AreaShop.configFileHidden), Charsets.UTF_8)
) { ) {
config = YamlConfiguration.loadConfiguration(custom); config = YamlConfiguration.loadConfiguration(custom);
if(config.getKeys(false).size() == 0) { if(config.getKeys(false).isEmpty()) {
AreaShop.warn("File 'config.yml' is empty, check for errors in the log."); AreaShop.warn("File 'config.yml' is empty, check for errors in the log.");
result = false; result = false;
} else { } else {
@ -958,12 +952,12 @@ public class FileManager extends Manager {
if(regionFile.exists() && regionFile.isFile() && !regionFile.isHidden()) { if(regionFile.exists() && regionFile.isFile() && !regionFile.isHidden()) {
// Load the region file from disk in UTF8 mode // Load the region file from disk in UTF8 mode
YamlConfiguration config; YamlConfiguration regionConfig;
try( try(
InputStreamReader reader = new InputStreamReader(new FileInputStream(regionFile), Charsets.UTF_8) InputStreamReader reader = new InputStreamReader(new FileInputStream(regionFile), Charsets.UTF_8)
) { ) {
config = YamlConfiguration.loadConfiguration(reader); regionConfig = YamlConfiguration.loadConfiguration(reader);
if(config.getKeys(false).size() == 0) { if(regionConfig.getKeys(false).isEmpty()) {
AreaShop.warn("Region file '" + regionFile.getName() + "' is empty, check for errors in the log."); AreaShop.warn("Region file '" + regionFile.getName() + "' is empty, check for errors in the log.");
} }
} catch(IOException e) { } catch(IOException e) {
@ -972,14 +966,14 @@ public class FileManager extends Manager {
} }
// Construct the correct type of region // Construct the correct type of region
String type = config.getString("general.type"); String type = regionConfig.getString("general.type");
GeneralRegion region; GeneralRegion region;
if(RegionType.RENT.getValue().equals(type)) { if(RegionType.RENT.getValue().equals(type)) {
region = new RentRegion(config); region = new RentRegion(regionConfig);
} else if(RegionType.BUY.getValue().equals(type)) { } else if(RegionType.BUY.getValue().equals(type)) {
region = new BuyRegion(config); region = new BuyRegion(regionConfig);
} else { } else {
noNamePaths.add(regionFile.getPath()); noRegionType.add(regionFile.getPath());
continue; continue;
} }
@ -1156,37 +1150,37 @@ public class FileManager extends Manager {
return; return;
} }
for(HashMap<String, String> rent : rents.values()) { for(HashMap<String, String> rent : rents.values()) {
YamlConfiguration config = new YamlConfiguration(); YamlConfiguration regionConfig = new YamlConfiguration();
config.set("general.name", rent.get("name").toLowerCase()); regionConfig.set("general.name", rent.get("name").toLowerCase());
config.set("general.type", "rent"); regionConfig.set("general.type", "rent");
config.set("general.world", rent.get("world")); regionConfig.set("general.world", rent.get("world"));
config.set("general.signs.0.location.world", rent.get("world")); regionConfig.set("general.signs.0.location.world", rent.get("world"));
config.set("general.signs.0.location.x", Double.parseDouble(rent.get("x"))); regionConfig.set("general.signs.0.location.x", Double.parseDouble(rent.get("x")));
config.set("general.signs.0.location.y", Double.parseDouble(rent.get("y"))); regionConfig.set("general.signs.0.location.y", Double.parseDouble(rent.get("y")));
config.set("general.signs.0.location.z", Double.parseDouble(rent.get("z"))); regionConfig.set("general.signs.0.location.z", Double.parseDouble(rent.get("z")));
config.set("rent.price", Double.parseDouble(rent.get("price"))); regionConfig.set("rent.price", Double.parseDouble(rent.get("price")));
config.set("rent.duration", rent.get("duration")); regionConfig.set("rent.duration", rent.get("duration"));
if(rent.get("restore") != null && !rent.get("restore").equals("general")) { if(rent.get("restore") != null && !rent.get("restore").equals("general")) {
config.set("general.enableRestore", rent.get("restore")); regionConfig.set("general.enableRestore", rent.get("restore"));
} }
if(rent.get("profile") != null && !rent.get("profile").equals("default")) { if(rent.get("profile") != null && !rent.get("profile").equals("default")) {
config.set("general.schematicProfile", rent.get("profile")); regionConfig.set("general.schematicProfile", rent.get("profile"));
} }
if(rent.get("tpx") != null) { if(rent.get("tpx") != null) {
config.set("general.teleportLocation.world", rent.get("world")); regionConfig.set("general.teleportLocation.world", rent.get("world"));
config.set("general.teleportLocation.x", Double.parseDouble(rent.get("tpx"))); regionConfig.set("general.teleportLocation.x", Double.parseDouble(rent.get("tpx")));
config.set("general.teleportLocation.y", Double.parseDouble(rent.get("tpy"))); regionConfig.set("general.teleportLocation.y", Double.parseDouble(rent.get("tpy")));
config.set("general.teleportLocation.z", Double.parseDouble(rent.get("tpz"))); regionConfig.set("general.teleportLocation.z", Double.parseDouble(rent.get("tpz")));
config.set("general.teleportLocation.yaw", rent.get("tpyaw")); regionConfig.set("general.teleportLocation.yaw", rent.get("tpyaw"));
config.set("general.teleportLocation.pitch", rent.get("tppitch")); regionConfig.set("general.teleportLocation.pitch", rent.get("tppitch"));
} }
if(rent.get("playeruuid") != null) { if(rent.get("playeruuid") != null) {
config.set("rent.renter", rent.get("playeruuid")); regionConfig.set("rent.renter", rent.get("playeruuid"));
config.set("rent.renterName", Utils.toName(rent.get("playeruuid"))); regionConfig.set("rent.renterName", Utils.toName(rent.get("playeruuid")));
config.set("rent.rentedUntil", Long.parseLong(rent.get("rented"))); regionConfig.set("rent.rentedUntil", Long.parseLong(rent.get("rented")));
} }
try { try {
config.save(new File(regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml")); regionConfig.save(new File(regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml"));
} catch(IOException e) { } catch(IOException e) {
AreaShop.warn(" Error: Could not save region file while converting: " + regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml"); AreaShop.warn(" Error: Could not save region file while converting: " + regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml");
} }
@ -1275,35 +1269,35 @@ public class FileManager extends Manager {
AreaShop.warn("Could not create directory: " + regionsFile.getAbsolutePath()); AreaShop.warn("Could not create directory: " + regionsFile.getAbsolutePath());
} }
for(HashMap<String, String> buy : buys.values()) { for(HashMap<String, String> buy : buys.values()) {
YamlConfiguration config = new YamlConfiguration(); YamlConfiguration regionConfig = new YamlConfiguration();
config.set("general.name", buy.get("name").toLowerCase()); regionConfig.set("general.name", buy.get("name").toLowerCase());
config.set("general.type", "buy"); regionConfig.set("general.type", "buy");
config.set("general.world", buy.get("world")); regionConfig.set("general.world", buy.get("world"));
config.set("general.signs.0.location.world", buy.get("world")); regionConfig.set("general.signs.0.location.world", buy.get("world"));
config.set("general.signs.0.location.x", Double.parseDouble(buy.get("x"))); regionConfig.set("general.signs.0.location.x", Double.parseDouble(buy.get("x")));
config.set("general.signs.0.location.y", Double.parseDouble(buy.get("y"))); regionConfig.set("general.signs.0.location.y", Double.parseDouble(buy.get("y")));
config.set("general.signs.0.location.z", Double.parseDouble(buy.get("z"))); regionConfig.set("general.signs.0.location.z", Double.parseDouble(buy.get("z")));
config.set("buy.price", Double.parseDouble(buy.get("price"))); regionConfig.set("buy.price", Double.parseDouble(buy.get("price")));
if(buy.get("restore") != null && !buy.get("restore").equals("general")) { if(buy.get("restore") != null && !buy.get("restore").equals("general")) {
config.set("general.enableRestore", buy.get("restore")); regionConfig.set("general.enableRestore", buy.get("restore"));
} }
if(buy.get("profile") != null && !buy.get("profile").equals("default")) { if(buy.get("profile") != null && !buy.get("profile").equals("default")) {
config.set("general.schematicProfile", buy.get("profile")); regionConfig.set("general.schematicProfile", buy.get("profile"));
} }
if(buy.get("tpx") != null) { if(buy.get("tpx") != null) {
config.set("general.teleportLocation.world", buy.get("world")); regionConfig.set("general.teleportLocation.world", buy.get("world"));
config.set("general.teleportLocation.x", Double.parseDouble(buy.get("tpx"))); regionConfig.set("general.teleportLocation.x", Double.parseDouble(buy.get("tpx")));
config.set("general.teleportLocation.y", Double.parseDouble(buy.get("tpy"))); regionConfig.set("general.teleportLocation.y", Double.parseDouble(buy.get("tpy")));
config.set("general.teleportLocation.z", Double.parseDouble(buy.get("tpz"))); regionConfig.set("general.teleportLocation.z", Double.parseDouble(buy.get("tpz")));
config.set("general.teleportLocation.yaw", buy.get("tpyaw")); regionConfig.set("general.teleportLocation.yaw", buy.get("tpyaw"));
config.set("general.teleportLocation.pitch", buy.get("tppitch")); regionConfig.set("general.teleportLocation.pitch", buy.get("tppitch"));
} }
if(buy.get("playeruuid") != null) { if(buy.get("playeruuid") != null) {
config.set("buy.buyer", buy.get("playeruuid")); regionConfig.set("buy.buyer", buy.get("playeruuid"));
config.set("buy.buyerName", Utils.toName(buy.get("playeruuid"))); regionConfig.set("buy.buyerName", Utils.toName(buy.get("playeruuid")));
} }
try { try {
config.save(new File(regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml")); regionConfig.save(new File(regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml"));
} catch(IOException e) { } catch(IOException e) {
AreaShop.warn(" Error: Could not save region file while converting: " + regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml"); AreaShop.warn(" Error: Could not save region file while converting: " + regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml");
} }
@ -1362,7 +1356,7 @@ public class FileManager extends Manager {
// Update versions file to 3 // Update versions file to 3
versions.put(AreaShop.versionFiles, 3); versions.put(AreaShop.versionFiles, 3);
saveVersions(); saveVersions();
if(getRegions().size() > 0) { if(!getRegions().isEmpty()) {
AreaShop.info(" Added last active time to regions (v2 to v3)"); AreaShop.info(" Added last active time to regions (v2 to v3)");
} }
} }

View File

@ -311,6 +311,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the name of the region. * Get the name of the region.
* @return The region name * @return The region name
*/ */
@Override
public String getName() { public String getName() {
return config.getString("general.name"); return config.getString("general.name");
} }
@ -365,6 +366,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the World of the region. * Get the World of the region.
* @return The World where the region is located * @return The World where the region is located
*/ */
@Override
public World getWorld() { public World getWorld() {
return Bukkit.getWorld(getWorldName()); return Bukkit.getWorld(getWorldName());
} }
@ -373,6 +375,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* 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 * @return The name of the world of the region
*/ */
@Override
public String getWorldName() { public String getWorldName() {
return getStringSetting("general.world"); return getStringSetting("general.world");
} }
@ -503,6 +506,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* 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 * @return The ProtectedRegion of WorldGuard or null if the region does not exist anymore
*/ */
@Override
public ProtectedRegion getRegion() { public ProtectedRegion getRegion() {
if(getWorld() == null if(getWorld() == null
|| plugin.getWorldGuard() == null || plugin.getWorldGuard() == null
@ -533,6 +537,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the width of the region (x-axis). * Get the width of the region (x-axis).
* @return The width of the region (x-axis) * @return The width of the region (x-axis)
*/ */
@Override
public int getWidth() { public int getWidth() {
if(getRegion() == null) { if(getRegion() == null) {
return 0; return 0;
@ -544,6 +549,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the depth of the region (z-axis). * Get the depth of the region (z-axis).
* @return The depth of the region (z-axis) * @return The depth of the region (z-axis)
*/ */
@Override
public int getDepth() { public int getDepth() {
if(getRegion() == null) { if(getRegion() == null) {
return 0; return 0;
@ -555,6 +561,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the height of the region (y-axis). * Get the height of the region (y-axis).
* @return The height of the region (y-axis) * @return The height of the region (y-axis)
*/ */
@Override
public int getHeight() { public int getHeight() {
if(getRegion() == null) { if(getRegion() == null) {
return 0; return 0;
@ -1414,12 +1421,12 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
String save = profileSection.getString(type.getValue() + ".save"); String save = profileSection.getString(type.getValue() + ".save");
String restore = profileSection.getString(type.getValue() + ".restore"); String restore = profileSection.getString(type.getValue() + ".restore");
// Save the region if needed // Save the region if needed
if(save != null && save.length() != 0) { if(save != null && !save.isEmpty()) {
save = Message.fromString(save).replacements(this).getSingle(); save = Message.fromString(save).replacements(this).getSingle();
saveRegionBlocks(save); saveRegionBlocks(save);
} }
// Restore the region if needed // Restore the region if needed
if(restore != null && restore.length() != 0) { if(restore != null && !restore.isEmpty()) {
restore = Message.fromString(restore).replacements(this).getSingle(); restore = Message.fromString(restore).replacements(this).getSingle();
restoreRegionBlocks(restore); restoreRegionBlocks(restore);
} }
@ -1438,7 +1445,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
} }
for(String command : commands) { for(String command : commands) {
if(command == null || command.length() == 0) { if(command == null || command.isEmpty()) {
continue; continue;
} }
// It is not ideal we have to disable language replacements here, but otherwise giving language variables // It is not ideal we have to disable language replacements here, but otherwise giving language variables
@ -1542,7 +1549,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
x2 = points.get(i + 1).getBlockX(); x2 = points.get(i + 1).getBlockX();
z2 = points.get(i + 1).getBlockZ(); z2 = points.get(i + 1).getBlockZ();
area = area + ((z1 + z2) * (x1 - x2)); area += ((z1 + z2) * (x1 - x2));
} }
x1 = points.get(numPoints - 1).getBlockX(); x1 = points.get(numPoints - 1).getBlockX();
@ -1550,7 +1557,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
x2 = points.get(0).getBlockX(); x2 = points.get(0).getBlockX();
z2 = points.get(0).getBlockZ(); z2 = points.get(0).getBlockZ();
area = area + ((z1 + z2) * (x1 - x2)); area += ((z1 + z2) * (x1 - x2));
area = Math.ceil(Math.abs(area) / 2); area = Math.ceil(Math.abs(area) / 2);
return (long)(area * getHeight()); return (long)(area * getHeight());
} }

View File

@ -148,8 +148,8 @@ public class RegionGroup {
*/ */
public Set<GeneralRegion> getMemberRegions() { public Set<GeneralRegion> getMemberRegions() {
Set<GeneralRegion> result = new HashSet<>(); Set<GeneralRegion> result = new HashSet<>();
for(String name : getMembers()) { for(String playerName : getMembers()) {
result.add(plugin.getFileManager().getRegion(name)); result.add(plugin.getFileManager().getRegion(playerName));
} }
return result; return result;
} }

View File

@ -316,7 +316,7 @@ public class RentRegion extends GeneralRegion {
*/ */
public double getMoneyBackAmount() { public double getMoneyBackAmount() {
Long currentTime = Calendar.getInstance().getTimeInMillis(); Long currentTime = Calendar.getInstance().getTimeInMillis();
Double timeLeft = (double)((getRentedUntil() - currentTime)); Double timeLeft = (double)(getRentedUntil() - currentTime);
double percentage = (getMoneyBackPercentage()) / 100.0; double percentage = (getMoneyBackPercentage()) / 100.0;
Double timePeriod = (double)(getDuration()); Double timePeriod = (double)(getDuration());
double periods = timeLeft / timePeriod; double periods = timeLeft / timePeriod;
@ -347,10 +347,8 @@ public class RentRegion extends GeneralRegion {
long now = Calendar.getInstance().getTimeInMillis(); long now = Calendar.getInstance().getTimeInMillis();
if(!isDeleted() && isRented() && now > getRentedUntil()) { if(!isDeleted() && isRented() && now > getRentedUntil()) {
// Extend rent if configured for that // Extend rent if configured for that
if(getBooleanSetting("rent.autoExtend")) { if(getBooleanSetting("rent.autoExtend") && extend()) {
if(extend()) { return false;
return false;
}
} }
// Send message to the player if online // Send message to the player if online

View File

@ -10,6 +10,10 @@ import java.util.HashMap;
public class Analytics { public class Analytics {
private Analytics() {
}
/** /**
* Start analytics tracking. * Start analytics tracking.
*/ */

View File

@ -49,8 +49,8 @@ public class GithubUpdateCheck {
this.author = author; this.author = author;
this.repository = repository; this.repository = repository;
this.currentVersion = plugin.getDescription().getVersion(); this.currentVersion = plugin.getDescription().getVersion();
this.versionComparator = (latestVersion, currentVersion) -> this.versionComparator = (latest, current) ->
!latestVersion.equalsIgnoreCase(currentVersion); !latest.equalsIgnoreCase(current);
this.checking = false; this.checking = false;
this.error = false; this.error = false;

View File

@ -9,6 +9,10 @@ import java.util.List;
public class Materials { public class Materials {
private Materials() {
}
private static boolean legacyMaterials = false; private static boolean legacyMaterials = false;
static { static {

View File

@ -265,7 +265,7 @@ public class Utils {
public static String millisToHumanFormat(long milliseconds) { public static String millisToHumanFormat(long milliseconds) {
long timeLeft = milliseconds + 500; long timeLeft = milliseconds + 500;
// To seconds // To seconds
timeLeft = timeLeft / 1000; timeLeft /= 1000;
if(timeLeft <= 0) { if(timeLeft <= 0) {
return Message.fromKey("timeleft-ended").getPlain(); return Message.fromKey("timeleft-ended").getPlain();
} else if(timeLeft == 1) { } else if(timeLeft == 1) {
@ -274,27 +274,27 @@ public class Utils {
return Message.fromKey("timeleft-seconds").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-seconds").replacements(timeLeft).getPlain();
} }
// To minutes // To minutes
timeLeft = timeLeft / 60; timeLeft /= 60;
if(timeLeft <= 120) { if(timeLeft <= 120) {
return Message.fromKey("timeleft-minutes").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-minutes").replacements(timeLeft).getPlain();
} }
// To hours // To hours
timeLeft = timeLeft / 60; timeLeft /= 60;
if(timeLeft <= 48) { if(timeLeft <= 48) {
return Message.fromKey("timeleft-hours").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-hours").replacements(timeLeft).getPlain();
} }
// To days // To days
timeLeft = timeLeft / 24; timeLeft /= 24;
if(timeLeft <= 60) { if(timeLeft <= 60) {
return Message.fromKey("timeleft-days").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-days").replacements(timeLeft).getPlain();
} }
// To months // To months
timeLeft = timeLeft / 30; timeLeft /= 30;
if(timeLeft <= 24) { if(timeLeft <= 24) {
return Message.fromKey("timeleft-months").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-months").replacements(timeLeft).getPlain();
} }
// To years // To years
timeLeft = timeLeft / 12; timeLeft /= 12;
return Message.fromKey("timeleft-years").replacements(timeLeft).getPlain(); return Message.fromKey("timeleft-years").replacements(timeLeft).getPlain();
} }
@ -599,7 +599,7 @@ public class Utils {
public static long durationStringToLong(String duration) { public static long durationStringToLong(String duration) {
if(duration == null) { if(duration == null) {
return 0; return 0;
} else if(duration.equalsIgnoreCase("disabled") || duration.equalsIgnoreCase("unlimited") || duration.length() == 0) { } else if(duration.equalsIgnoreCase("disabled") || duration.equalsIgnoreCase("unlimited") || duration.isEmpty()) {
return -1; return -1;
} else if(duration.indexOf(' ') == -1) { } else if(duration.indexOf(' ') == -1) {
return 0; return 0;
@ -647,7 +647,7 @@ public class Utils {
if(config.isLong(path) || config.isInt(path)) { if(config.isLong(path) || config.isInt(path)) {
long setting = config.getLong(path); long setting = config.getLong(path);
if(setting != -1) { if(setting != -1) {
setting = setting * 1000; setting *= 1000;
} }
return setting; return setting;
} else { } else {
@ -665,7 +665,7 @@ public class Utils {
if(config.isLong(path) || config.isInt(path)) { if(config.isLong(path) || config.isInt(path)) {
long setting = config.getLong(path); long setting = config.getLong(path);
if(setting != -1) { if(setting != -1) {
setting = setting * 60 * 1000; setting *= 60 * 1000;
} }
return setting; return setting;
} else { } else {
@ -683,7 +683,7 @@ public class Utils {
try { try {
number = Long.parseLong(input); number = Long.parseLong(input);
if(number != -1) { if(number != -1) {
number = number * 60 * 1000; number *= 60 * 1000;
} }
return number; return number;
} catch(NumberFormatException e) { } catch(NumberFormatException e) {
@ -701,7 +701,7 @@ public class Utils {
try { try {
number = Long.parseLong(input); number = Long.parseLong(input);
if(number != -1) { if(number != -1) {
number = number * 1000; number *= 1000;
} }
return number; return number;
} catch(NumberFormatException e) { } catch(NumberFormatException e) {

View File

@ -2,29 +2,29 @@ package me.wiefferink.areashop.tools;
public class Value<T> { public class Value<T> {
private T value; private T content;
/** /**
* Create a container with a default value. * Create a container with a default content.
* @param value The value to set * @param content The content to set
*/ */
public Value(T value) { public Value(T content) {
this.value = value; this.content = content;
} }
/** /**
* Get the stored value. * Get the stored content.
* @return The stored value * @return The stored content
*/ */
public T get() { public T get() {
return value; return content;
} }
/** /**
* Set the value. * Set the content.
* @param value The new value * @param value The new content
*/ */
public void set(T value) { public void set(T value) {
this.value = value; this.content = value;
} }
} }

View File

@ -4,9 +4,9 @@ import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
public class WorldEditSelection { public class WorldEditSelection {
private World world; private final World world;
private Location minimum; private final Location minimum;
private Location maximum; private final Location maximum;
/** /**
* Craete a WorldEditSelection. * Craete a WorldEditSelection.

View File

@ -36,9 +36,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class WorldEditHandler7_beta_1 extends WorldEditInterface { public class WorldEditHandler7_beta_1 extends WorldEditInterface {
@ -66,8 +63,9 @@ public class WorldEditHandler7_beta_1 extends WorldEditInterface {
ClipboardFormat format = null; ClipboardFormat format = null;
for (ClipboardFormat formatOption : ClipboardFormats.getAll()) { for (ClipboardFormat formatOption : ClipboardFormats.getAll()) {
for (String extension : formatOption.getFileExtensions()) { for (String extension : formatOption.getFileExtensions()) {
if (new File(rawFile.getAbsolutePath() + "." + extension).exists()) { File fileOption = new File(rawFile.getAbsolutePath() + "." + extension);
file = new File(rawFile.getAbsolutePath() + "." + extension); if (fileOption.exists()) {
file = fileOption;
format = formatOption; format = formatOption;
} }
} }

View File

@ -36,9 +36,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class WorldEditHandler7_beta_4 extends WorldEditInterface { public class WorldEditHandler7_beta_4 extends WorldEditInterface {
@ -66,8 +63,9 @@ public class WorldEditHandler7_beta_4 extends WorldEditInterface {
ClipboardFormat format = null; ClipboardFormat format = null;
for (ClipboardFormat formatOption : ClipboardFormats.getAll()) { for (ClipboardFormat formatOption : ClipboardFormats.getAll()) {
for (String extension : formatOption.getFileExtensions()) { for (String extension : formatOption.getFileExtensions()) {
if (new File(rawFile.getAbsolutePath() + "." + extension).exists()) { File fileOption = new File(rawFile.getAbsolutePath() + "." + extension);
file = new File(rawFile.getAbsolutePath() + "." + extension); if (fileOption.exists()) {
file = fileOption;
format = formatOption; format = formatOption;
} }
} }