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.
*/
@Override
public void onEnable() {
AreaShop.instance = this;
Do.init(this);
@ -201,10 +202,10 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
if(rawWgVersion.contains("-SNAPSHOT;")) {
String buildNumber = rawWgVersion.substring(rawWgVersion.indexOf("-SNAPSHOT;") + 10);
if(buildNumber.contains("-")) {
buildNumber = buildNumber.substring(0, buildNumber.indexOf("-"));
try {
buildNumber = buildNumber.substring(0, buildNumber.indexOf('-'));
if (Utils.isNumeric(buildNumber)) {
build = Integer.parseInt(buildNumber);
} catch(NumberFormatException e) {
} else {
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
fileManager = new 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
if(wgVersion != null) {
@ -373,7 +375,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
"AreaShop"
).withVersionComparator((latestVersion, currentVersion) ->
!cleanVersion(latestVersion).equals(cleanVersion(currentVersion))
).checkUpdate((result) -> {
).checkUpdate(result -> {
AreaShop.debug("Update check result:", result);
if(!result.hasUpdate()) {
return;
@ -422,6 +424,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
/**
* Called on shutdown or reload of the server.
*/
@Override
public void onDisable() {
Bukkit.getServer().getScheduler().cancelTasks(this);
@ -500,6 +503,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* Function to get the WorldGuard plugin.
* @return WorldGuardPlugin
*/
@Override
public WorldGuardPlugin getWorldGuard() {
return worldGuard;
}
@ -525,6 +529,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* Function to get the WorldEdit plugin.
* @return WorldEditPlugin
*/
@Override
public WorldEditPlugin getWorldEdit() {
return worldEdit;
}
@ -771,6 +776,7 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
* 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
*/
@Override
public void debugI(Object... message) {
AreaShop.debug(StringUtils.join(message, " "));
}

View File

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

View File

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

View File

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

View File

@ -53,7 +53,7 @@ public class GroupaddCommand extends CommandAreaShop {
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) {
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
@ -66,10 +66,10 @@ public class GroupaddCommand extends CommandAreaShop {
regionsFailed.add(region);
}
}
if(regionsSuccess.size() != 0) {
if(!regionsSuccess.isEmpty()) {
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"));
}
// 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;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.size() == 0) {
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
@ -67,10 +67,10 @@ public class GroupdelCommand extends CommandAreaShop {
regionsFailed.add(region);
}
}
if(regionsSuccess.size() != 0) {
if(!regionsSuccess.isEmpty()) {
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"));
}
// 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;
}
Set<String> members = group.getMembers();
if(members.size() == 0) {
if(members.isEmpty()) {
plugin.message(sender, "groupinfo-noMembers", group.getName());
} else {
plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members));

View File

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

View File

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

View File

@ -330,7 +330,7 @@ public class ImportJob {
String buyPrice = from.getString("economic-settings.cost-per-unit.buy");
String sellPrice = from.getString("economic-settings.cost-per-unit.selling-price");
// 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
String unitSuffix = "";
@ -411,8 +411,8 @@ public class ImportJob {
}
private static class TimeUnit {
public long minutes;
public String identifier;
public final long minutes;
public final String identifier;
TimeUnit(long minutes, String identifier) {
this.minutes = minutes;

View File

@ -113,9 +113,9 @@ public class InfoCommand extends CommandAreaShop {
}
// Page status
if(totalPages > 1) {
String pageString = "" + page;
StringBuilder pageString = new StringBuilder("" + page);
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));
if(page < totalPages) {

View File

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

View File

@ -157,33 +157,16 @@ public class StackCommand extends CommandAreaShop {
current++;
if(current < amount) {
// Create the region name
String counterName = 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;
}
String regionName = countToName(nameTemplate, counter);
while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) {
counter++;
counterName = counter + "";
minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName = "0" + counterName;
}
if(nameTemplate.contains("#")) {
regionName = nameTemplate.replace("#", counterName);
} else {
regionName = nameTemplate + counterName;
}
regionName = countToName(nameTemplate, counter);
}
// 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 maximum = maximumVector.clone().add(finalShift.clone().multiply(current));
// Check for out of bounds
if(minimum.getBlockY() < 0) {
tooLow++;
@ -194,6 +177,7 @@ public class StackCommand extends CommandAreaShop {
}
ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum);
manager.addRegion(region);
// Add the region to AreaShop
if(rentRegions) {
RentRegion rent = new RentRegion(regionName, selection.getWorld());
@ -236,6 +220,26 @@ public class StackCommand extends CommandAreaShop {
}.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
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();

View File

@ -59,12 +59,13 @@ public class TeleportCommand extends CommandAreaShop {
plugin.message(player, "teleport-noRentOrBuy", args[1]);
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

View File

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

View File

@ -147,7 +147,7 @@ public class TeleportFeature extends RegionFeature {
int maxTries = plugin.getConfig().getInt("maximumTries");
// 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 continueThisDirection;

View File

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

View File

@ -194,7 +194,7 @@ public class SignsFeature extends RegionFeature {
RegionManager regionManager = plugin.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) {
if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) {
boolean first = true;
@ -224,10 +224,10 @@ public class SignsFeature extends RegionFeature {
}
}
boolean priceSet = fourthLine != null && fourthLine.length() != 0;
boolean durationSet = thirdLine != null && thirdLine.length() != 0;
boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct
if(secondLine == null || secondLine.length() == 0) {
if(secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion");
return;
}
@ -246,7 +246,7 @@ public class SignsFeature extends RegionFeature {
plugin.message(player, "setup-alreadyOtherWorld");
} else if(addResult == FileManager.AddResult.NOPERMISSION) {
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");
} else {
double price = 0.0;
@ -306,7 +306,7 @@ public class SignsFeature extends RegionFeature {
RegionManager regionManager = plugin.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) {
if(secondLine == null || secondLine.isEmpty()) {
Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
if(regions != null) {
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
if(secondLine == null || secondLine.length() == 0) {
if(secondLine == null || secondLine.isEmpty()) {
plugin.message(player, "setup-noRegion");
return;
}
@ -408,7 +408,7 @@ public class SignsFeature extends RegionFeature {
String thirdLine = event.getLine(2);
GeneralRegion region;
if(secondLine != null && secondLine.length() != 0) {
if(secondLine != null && !secondLine.isEmpty()) {
// Get region by secondLine of the sign
region = plugin.getFileManager().getRegion(secondLine);
if(region == null) {
@ -428,7 +428,7 @@ public class SignsFeature extends RegionFeature {
region = regions.get(0);
}
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);
plugin.message(player, "addsign-success", region);
} else {
@ -516,7 +516,7 @@ public class SignsFeature extends RegionFeature {
public boolean update() {
boolean result = true;
for(RegionSign sign : signs.values()) {
result = result & sign.update();
result &= sign.update();
}
return result;
}
@ -528,7 +528,7 @@ public class SignsFeature extends RegionFeature {
public boolean needsPeriodicUpdate() {
boolean result = false;
for(RegionSign sign : signs.values()) {
result = result | sign.needsPeriodicUpdate();
result |= sign.needsPeriodicUpdate();
}
return result;
}
@ -577,7 +577,7 @@ public class SignsFeature extends RegionFeature {
getRegion().setSetting(signPath + "location", Utils.locationToConfig(location));
getRegion().setSetting(signPath + "facing", facing != null ? facing.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);
}
// Add to the map
@ -588,28 +588,4 @@ public class SignsFeature extends RegionFeature {
.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.
* @return The list with AreaShop commands
*/
public ArrayList<CommandAreaShop> getCommands() {
public List<CommandAreaShop> getCommands() {
return commands;
}
@ -114,7 +114,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
plugin.message(target, "help-alias");
for(CommandAreaShop command : commands) {
String help = command.getHelp(target);
if(help != null && help.length() != 0) {
if(help != null && !help.isEmpty()) {
messages.add(help);
}
}
@ -130,11 +130,13 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
plugin.message(sender, "general-notReady");
return true;
}
// Redirect `/as info player <player>` to `/as me <player>`
if(args.length == 3 && "info".equals(args[0]) && "player".equals(args[1])) {
args[0] = "me";
args[1] = args[2];
}
// Execute command
boolean executed = false;
for(int i = 0; i < commands.size() && !executed; i++) {
@ -143,16 +145,21 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
executed = true;
}
}
if(!executed && args.length == 0) {
this.showHelp(sender);
} else if(!executed && args.length > 0) {
// 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");
// Show help
if (!executed) {
if (args.length == 0) {
this.showHelp(sender);
} 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;
}
@ -181,7 +188,7 @@ public class CommandManager extends Manager implements CommandExecutor, TabCompl
}
}
// Filter and sort the results
if(result.size() > 0) {
if(!result.isEmpty()) {
SortedSet<String> set = new TreeSet<>();
for(String suggestion : result) {
if(suggestion.toLowerCase().startsWith(toCompletePrefix)) {

View File

@ -40,13 +40,11 @@ public class FeatureManager extends Manager {
for(Class<? extends RegionFeature> clazz : featureClasses) {
try {
Constructor<? extends RegionFeature> constructor = clazz.getConstructor();
try {
RegionFeature feature = constructor.newInstance();
feature.listen();
globalFeatures.add(feature);
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
AreaShop.error("Failed to instantiate global feature:", clazz, e);
}
RegionFeature feature = constructor.newInstance();
feature.listen();
globalFeatures.add(feature);
} catch(InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
AreaShop.error("Failed to instantiate global feature:", clazz, e);
} catch(NoSuchMethodException e) {
// 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());
}
}
RegionGroup[] groups = getGroups().toArray(new RegionGroup[getGroups().size()]);
for(RegionGroup group : groups) {
RegionGroup[] regionGroups = getGroups().toArray(new RegionGroup[0]);
for(RegionGroup group : regionGroups) {
group.removeMember(rent);
}
rent.resetRegionFlags();
@ -738,16 +738,14 @@ public class FileManager extends Manager {
File file = new File(versionPath);
if(file.exists()) {
// Load versions from the file
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(versionPath));
versions = (HashMap<String, Integer>)input.readObject();
input.close();
try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(versionPath))) {
versions = (HashMap<String, Integer>) input.readObject();
} catch(IOException | ClassNotFoundException | ClassCastException e) {
AreaShop.warn("Something went wrong reading file: " + versionPath);
versions = null;
}
}
if(versions == null || versions.size() == 0) {
if(versions == null || versions.isEmpty()) {
versions = new HashMap<>();
versions.put(AreaShop.versionFiles, 0);
this.saveVersions();
@ -761,10 +759,8 @@ public class FileManager extends Manager {
if(!(new File(versionPath).exists())) {
AreaShop.debug("versions file created, this should happen only after installing or upgrading the plugin");
}
try {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(versionPath));
try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(versionPath))) {
output.writeObject(versions);
output.close();
} catch(IOException e) {
AreaShop.warn("File could not be saved: " + versionPath);
}
@ -820,8 +816,6 @@ public class FileManager extends Manager {
while((read = input.read(bytes)) != -1) {
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");
} catch(IOException e) {
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)
) {
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.");
result = false;
}
@ -874,7 +868,7 @@ public class FileManager extends Manager {
InputStreamReader hidden = new InputStreamReader(plugin.getResource(AreaShop.configFileHidden), Charsets.UTF_8)
) {
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.");
result = false;
} else {
@ -958,12 +952,12 @@ public class FileManager extends Manager {
if(regionFile.exists() && regionFile.isFile() && !regionFile.isHidden()) {
// Load the region file from disk in UTF8 mode
YamlConfiguration config;
YamlConfiguration regionConfig;
try(
InputStreamReader reader = new InputStreamReader(new FileInputStream(regionFile), Charsets.UTF_8)
) {
config = YamlConfiguration.loadConfiguration(reader);
if(config.getKeys(false).size() == 0) {
regionConfig = YamlConfiguration.loadConfiguration(reader);
if(regionConfig.getKeys(false).isEmpty()) {
AreaShop.warn("Region file '" + regionFile.getName() + "' is empty, check for errors in the log.");
}
} catch(IOException e) {
@ -972,14 +966,14 @@ public class FileManager extends Manager {
}
// Construct the correct type of region
String type = config.getString("general.type");
String type = regionConfig.getString("general.type");
GeneralRegion region;
if(RegionType.RENT.getValue().equals(type)) {
region = new RentRegion(config);
region = new RentRegion(regionConfig);
} else if(RegionType.BUY.getValue().equals(type)) {
region = new BuyRegion(config);
region = new BuyRegion(regionConfig);
} else {
noNamePaths.add(regionFile.getPath());
noRegionType.add(regionFile.getPath());
continue;
}
@ -1156,37 +1150,37 @@ public class FileManager extends Manager {
return;
}
for(HashMap<String, String> rent : rents.values()) {
YamlConfiguration config = new YamlConfiguration();
config.set("general.name", rent.get("name").toLowerCase());
config.set("general.type", "rent");
config.set("general.world", rent.get("world"));
config.set("general.signs.0.location.world", rent.get("world"));
config.set("general.signs.0.location.x", Double.parseDouble(rent.get("x")));
config.set("general.signs.0.location.y", Double.parseDouble(rent.get("y")));
config.set("general.signs.0.location.z", Double.parseDouble(rent.get("z")));
config.set("rent.price", Double.parseDouble(rent.get("price")));
config.set("rent.duration", rent.get("duration"));
YamlConfiguration regionConfig = new YamlConfiguration();
regionConfig.set("general.name", rent.get("name").toLowerCase());
regionConfig.set("general.type", "rent");
regionConfig.set("general.world", rent.get("world"));
regionConfig.set("general.signs.0.location.world", rent.get("world"));
regionConfig.set("general.signs.0.location.x", Double.parseDouble(rent.get("x")));
regionConfig.set("general.signs.0.location.y", Double.parseDouble(rent.get("y")));
regionConfig.set("general.signs.0.location.z", Double.parseDouble(rent.get("z")));
regionConfig.set("rent.price", Double.parseDouble(rent.get("price")));
regionConfig.set("rent.duration", rent.get("duration"));
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")) {
config.set("general.schematicProfile", rent.get("profile"));
regionConfig.set("general.schematicProfile", rent.get("profile"));
}
if(rent.get("tpx") != null) {
config.set("general.teleportLocation.world", rent.get("world"));
config.set("general.teleportLocation.x", Double.parseDouble(rent.get("tpx")));
config.set("general.teleportLocation.y", Double.parseDouble(rent.get("tpy")));
config.set("general.teleportLocation.z", Double.parseDouble(rent.get("tpz")));
config.set("general.teleportLocation.yaw", rent.get("tpyaw"));
config.set("general.teleportLocation.pitch", rent.get("tppitch"));
regionConfig.set("general.teleportLocation.world", rent.get("world"));
regionConfig.set("general.teleportLocation.x", Double.parseDouble(rent.get("tpx")));
regionConfig.set("general.teleportLocation.y", Double.parseDouble(rent.get("tpy")));
regionConfig.set("general.teleportLocation.z", Double.parseDouble(rent.get("tpz")));
regionConfig.set("general.teleportLocation.yaw", rent.get("tpyaw"));
regionConfig.set("general.teleportLocation.pitch", rent.get("tppitch"));
}
if(rent.get("playeruuid") != null) {
config.set("rent.renter", rent.get("playeruuid"));
config.set("rent.renterName", Utils.toName(rent.get("playeruuid")));
config.set("rent.rentedUntil", Long.parseLong(rent.get("rented")));
regionConfig.set("rent.renter", rent.get("playeruuid"));
regionConfig.set("rent.renterName", Utils.toName(rent.get("playeruuid")));
regionConfig.set("rent.rentedUntil", Long.parseLong(rent.get("rented")));
}
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) {
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());
}
for(HashMap<String, String> buy : buys.values()) {
YamlConfiguration config = new YamlConfiguration();
config.set("general.name", buy.get("name").toLowerCase());
config.set("general.type", "buy");
config.set("general.world", buy.get("world"));
config.set("general.signs.0.location.world", buy.get("world"));
config.set("general.signs.0.location.x", Double.parseDouble(buy.get("x")));
config.set("general.signs.0.location.y", Double.parseDouble(buy.get("y")));
config.set("general.signs.0.location.z", Double.parseDouble(buy.get("z")));
config.set("buy.price", Double.parseDouble(buy.get("price")));
YamlConfiguration regionConfig = new YamlConfiguration();
regionConfig.set("general.name", buy.get("name").toLowerCase());
regionConfig.set("general.type", "buy");
regionConfig.set("general.world", buy.get("world"));
regionConfig.set("general.signs.0.location.world", buy.get("world"));
regionConfig.set("general.signs.0.location.x", Double.parseDouble(buy.get("x")));
regionConfig.set("general.signs.0.location.y", Double.parseDouble(buy.get("y")));
regionConfig.set("general.signs.0.location.z", Double.parseDouble(buy.get("z")));
regionConfig.set("buy.price", Double.parseDouble(buy.get("price")));
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")) {
config.set("general.schematicProfile", buy.get("profile"));
regionConfig.set("general.schematicProfile", buy.get("profile"));
}
if(buy.get("tpx") != null) {
config.set("general.teleportLocation.world", buy.get("world"));
config.set("general.teleportLocation.x", Double.parseDouble(buy.get("tpx")));
config.set("general.teleportLocation.y", Double.parseDouble(buy.get("tpy")));
config.set("general.teleportLocation.z", Double.parseDouble(buy.get("tpz")));
config.set("general.teleportLocation.yaw", buy.get("tpyaw"));
config.set("general.teleportLocation.pitch", buy.get("tppitch"));
regionConfig.set("general.teleportLocation.world", buy.get("world"));
regionConfig.set("general.teleportLocation.x", Double.parseDouble(buy.get("tpx")));
regionConfig.set("general.teleportLocation.y", Double.parseDouble(buy.get("tpy")));
regionConfig.set("general.teleportLocation.z", Double.parseDouble(buy.get("tpz")));
regionConfig.set("general.teleportLocation.yaw", buy.get("tpyaw"));
regionConfig.set("general.teleportLocation.pitch", buy.get("tppitch"));
}
if(buy.get("playeruuid") != null) {
config.set("buy.buyer", buy.get("playeruuid"));
config.set("buy.buyerName", Utils.toName(buy.get("playeruuid")));
regionConfig.set("buy.buyer", buy.get("playeruuid"));
regionConfig.set("buy.buyerName", Utils.toName(buy.get("playeruuid")));
}
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) {
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
versions.put(AreaShop.versionFiles, 3);
saveVersions();
if(getRegions().size() > 0) {
if(!getRegions().isEmpty()) {
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.
* @return The region name
*/
@Override
public String getName() {
return config.getString("general.name");
}
@ -365,6 +366,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the World of the region.
* @return The World where the region is located
*/
@Override
public World getWorld() {
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.
* @return The name of the world of the region
*/
@Override
public String getWorldName() {
return getStringSetting("general.world");
}
@ -503,6 +506,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the WorldGuard region associated with this AreaShop region.
* @return The ProtectedRegion of WorldGuard or null if the region does not exist anymore
*/
@Override
public ProtectedRegion getRegion() {
if(getWorld() == null
|| plugin.getWorldGuard() == null
@ -533,6 +537,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the width of the region (x-axis).
* @return The width of the region (x-axis)
*/
@Override
public int getWidth() {
if(getRegion() == null) {
return 0;
@ -544,6 +549,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the depth of the region (z-axis).
* @return The depth of the region (z-axis)
*/
@Override
public int getDepth() {
if(getRegion() == null) {
return 0;
@ -555,6 +561,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
* Get the height of the region (y-axis).
* @return The height of the region (y-axis)
*/
@Override
public int getHeight() {
if(getRegion() == null) {
return 0;
@ -1414,12 +1421,12 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
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) {
if(save != null && !save.isEmpty()) {
save = Message.fromString(save).replacements(this).getSingle();
saveRegionBlocks(save);
}
// Restore the region if needed
if(restore != null && restore.length() != 0) {
if(restore != null && !restore.isEmpty()) {
restore = Message.fromString(restore).replacements(this).getSingle();
restoreRegionBlocks(restore);
}
@ -1438,7 +1445,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
}
for(String command : commands) {
if(command == null || command.length() == 0) {
if(command == null || command.isEmpty()) {
continue;
}
// 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();
z2 = points.get(i + 1).getBlockZ();
area = area + ((z1 + z2) * (x1 - x2));
area += ((z1 + z2) * (x1 - x2));
}
x1 = points.get(numPoints - 1).getBlockX();
@ -1550,7 +1557,7 @@ public abstract class GeneralRegion implements GeneralRegionInterface, Comparabl
x2 = points.get(0).getBlockX();
z2 = points.get(0).getBlockZ();
area = area + ((z1 + z2) * (x1 - x2));
area += ((z1 + z2) * (x1 - x2));
area = Math.ceil(Math.abs(area) / 2);
return (long)(area * getHeight());
}

View File

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

View File

@ -316,7 +316,7 @@ public class RentRegion extends GeneralRegion {
*/
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 periods = timeLeft / timePeriod;
@ -347,10 +347,8 @@ public class RentRegion extends GeneralRegion {
long now = Calendar.getInstance().getTimeInMillis();
if(!isDeleted() && isRented() && now > getRentedUntil()) {
// Extend rent if configured for that
if(getBooleanSetting("rent.autoExtend")) {
if(extend()) {
return false;
}
if(getBooleanSetting("rent.autoExtend") && extend()) {
return false;
}
// Send message to the player if online

View File

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

View File

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

View File

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

View File

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

View File

@ -2,29 +2,29 @@ package me.wiefferink.areashop.tools;
public class Value<T> {
private T value;
private T content;
/**
* Create a container with a default value.
* @param value The value to set
* Create a container with a default content.
* @param content The content to set
*/
public Value(T value) {
this.value = value;
public Value(T content) {
this.content = content;
}
/**
* Get the stored value.
* @return The stored value
* Get the stored content.
* @return The stored content
*/
public T get() {
return value;
return content;
}
/**
* Set the value.
* @param value The new value
* Set the content.
* @param value The new content
*/
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;
public class WorldEditSelection {
private World world;
private Location minimum;
private Location maximum;
private final World world;
private final Location minimum;
private final Location maximum;
/**
* Craete a WorldEditSelection.

View File

@ -36,9 +36,6 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 {
@ -66,8 +63,9 @@ public class WorldEditHandler7_beta_1 extends WorldEditInterface {
ClipboardFormat format = null;
for (ClipboardFormat formatOption : ClipboardFormats.getAll()) {
for (String extension : formatOption.getFileExtensions()) {
if (new File(rawFile.getAbsolutePath() + "." + extension).exists()) {
file = new File(rawFile.getAbsolutePath() + "." + extension);
File fileOption = new File(rawFile.getAbsolutePath() + "." + extension);
if (fileOption.exists()) {
file = fileOption;
format = formatOption;
}
}

View File

@ -36,9 +36,6 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 {
@ -66,8 +63,9 @@ public class WorldEditHandler7_beta_4 extends WorldEditInterface {
ClipboardFormat format = null;
for (ClipboardFormat formatOption : ClipboardFormats.getAll()) {
for (String extension : formatOption.getFileExtensions()) {
if (new File(rawFile.getAbsolutePath() + "." + extension).exists()) {
file = new File(rawFile.getAbsolutePath() + "." + extension);
File fileOption = new File(rawFile.getAbsolutePath() + "." + extension);
if (fileOption.exists()) {
file = fileOption;
format = formatOption;
}
}