name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
AreaShop_GeneralRegion_getCurrent_rdh
/** * Get the current number of regions in the group that is the limiting factor, assuming actionAllowed() is false. * * @return The current number of regions the player has */ public int getCurrent() { return current; }
3.26
AreaShop_GeneralRegion_getStringListSetting_rdh
/** * Get a string list setting for this region, defined as follows * - If the region has the setting in its own file (/regions/regionName.yml), use that * - If the region has groups, use the setting defined by the most important group, if any * - Otherwise fallback to the default.yml file setting * * @param path * The path to get the setting of * @return The value of the setting */public List<String> getStringListSetting(String path) { if (config.isSet(path)) { return config.getStringList(path); } List<String> result = null; int priority = Integer.MIN_VALUE; boolean found = false; for (RegionGroup group : plugin.getFileManager().getGroups()) { if ((group.isMember(this) && group.getSettings().isSet(path)) && (group.getPriority() > priority)) { result = group.getSettings().getStringList(path); priority = group.getPriority(); found = true; } } if (found) { return result; } if (this.getFileManager().getRegionSettings().isSet(path)) { return this.getFileManager().getRegionSettings().getStringList(path); } else { return this.getFileManager().getFallbackRegionSettings().getStringList(path); } }
3.26
AreaShop_GeneralRegion_getLandlord_rdh
/** * Get the landlord of this region (the player that receives any revenue from this region). * * @return The UUID of the landlord of this region */ public UUID getLandlord() { String landlord = getStringSetting("general.landlord"); if ((landlord != null) && (!landlord.isEmpty())) { try {return UUID.fromString(landlord); } catch (IllegalArgumentException e) { // Incorrect UUID } } String landlordName = getStringSetting("general.landlordName"); if ((landlordName != null) && (!landlordName.isEmpty())) {@SuppressWarnings("deprecation") OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(landlordName); if (offlinePlayer != null) { return offlinePlayer.getUniqueId(); } } return null; }
3.26
AreaShop_GeneralRegion_saveNow_rdh
/** * Save this region to disk now, using this method could slow down the plugin, normally saveRequired() should be used. * * @return true if the region is saved successfully, otherwise false */ public boolean saveNow() { if (isDeleted()) {return false; } saveRequired = false;File file = new File(((plugin.getFileManager().getRegionFolder() + File.separator) + getName().toLowerCase()) + ".yml"); try { config.save(file); return true; } catch (IOException e) { return false; } }
3.26
AreaShop_GeneralRegion_getRegion_rdh
/** * 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)) || (plugin.getRegionManager(getWorld()) == null)) || (plugin.getRegionManager(getWorld()).getRegion(getName()) == null)) { return null; } return plugin.getRegionManager(getWorld()).getRegion(getName()); }
3.26
AreaShop_GeneralRegion_getMinimumPoint_rdh
/** * Get the minimum corner of the region. * * @return Vector */ public Vector getMinimumPoint() { return plugin.getWorldGuardHandler().getMinimumPoint(getRegion()); }
3.26
AreaShop_GeneralRegion_getDoubleSetting_rdh
/** * Get a double setting for this region, defined as follows * - If the region has the setting in its own file (/regions/regionName.yml), use that * - If the region has groups, use the setting defined by the most important group, if any * - Otherwise fallback to the default.yml file setting * * @param path * The path to get the setting of * @return The value of the setting */ public double getDoubleSetting(String path) { if (config.isSet(path)) { return config.getDouble(path); } double result = 0; int priority = Integer.MIN_VALUE; boolean found = false; for (RegionGroup group : plugin.getFileManager().getGroups()) { if ((group.isMember(this) && group.getSettings().isSet(path)) && (group.getPriority() > priority)) { result = group.getSettings().getDouble(path); priority = group.getPriority(); found = true; } } if (found) { return result; } if (this.getFileManager().getRegionSettings().isSet(path)) { return this.getFileManager().getRegionSettings().getDouble(path); } else { return this.getFileManager().getFallbackRegionSettings().getDouble(path); } }
3.26
AreaShop_SoldRegionEvent_getOldBuyer_rdh
/** * Get the player that the region is sold for. * * @return The UUID of the player that the region is sold for */ public UUID getOldBuyer() { return oldBuyer; }
3.26
AreaShop_SoldRegionEvent_getRefundedMoney_rdh
/** * Get the amount that is paid back to the player. * * @return The amount of money paid back to the player */ public double getRefundedMoney() { return refundedMoney; }
3.26
AreaShop_RentRegion_extend_rdh
/** * Try to extend the rent for the current owner, respecting all restrictions. * * @return true if successful, otherwise false */ public boolean extend() { if (!isRented()) { return false; } OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(getRenter()); return (offlinePlayer != null) && rent(offlinePlayer); }
3.26
AreaShop_RentRegion_unRent_rdh
/** * Unrent a region, reset to unrented. * * @param giveMoneyBack * true if money should be given back to the player, false otherwise * @param executor * The CommandSender that should get the cancelled message if there is any, or null * @return true if unrenting succeeded, othwerwise false */ @SuppressWarnings("deprecation") public boolean unRent(boolean giveMoneyBack, CommandSender executor) { boolean own = (executor instanceof Player) && this.isRenter(((Player) (executor))); if (executor != null) { if ((!executor.hasPermission("areashop.unrent")) && (!own)) { message(executor, "unrent-noPermissionOther"); return false; } if (((!executor.hasPermission("areashop.unrent")) && (!executor.hasPermission("areashop.unrentown"))) && own) { message(executor, "unrent-noPermission"); return false; } } if (plugin.getEconomy() == null) { return false; } // Broadcast and check event UnrentingRegionEvent event = new UnrentingRegionEvent(this); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { message(executor, "general-cancelled", event.getReason()); return false; } // Do a payback double moneyBack = getMoneyBackAmount(); if ((moneyBack > 0) && giveMoneyBack) { boolean noPayBack = false; OfflinePlayer landlordPlayer = null; if (getLandlord() != null) { landlordPlayer = Bukkit.getOfflinePlayer(getLandlord()); } String landlordName = getLandlordName(); EconomyResponse r; if (landlordName != null) { if ((landlordPlayer != null) && (landlordPlayer.getName() != null)) { r = plugin.getEconomy().withdrawPlayer(landlordPlayer, getWorldName(), moneyBack); } else { r = plugin.getEconomy().withdrawPlayer(landlordName, getWorldName(), moneyBack); } if ((r == null) || (!r.transactionSuccess())) { noPayBack = true; } } // Give back the money OfflinePlayer v39 = Bukkit.getOfflinePlayer(getRenter()); if ((v39 != null) && (!noPayBack)) { r = null; boolean error = false; try { if (v39.getName() != null) { r = plugin.getEconomy().depositPlayer(v39, getWorldName(), moneyBack); } else if (getPlayerName() != null) { r = plugin.getEconomy().depositPlayer(getPlayerName(), getWorldName(), moneyBack); } } catch (Exception e) { error = true; } if ((error || (r == null)) || (!r.transactionSuccess())) { AreaShop.warn((("Something went wrong with paying back to " + getPlayerName()) + " money while unrenting region ") + getName()); } } } // Handle schematic save/restore (while %uuid% is still available) handleSchematicEvent(RegionEvent.UNRENTED); // Send message: before actual removal of the renter so that it is still available for variables message(executor, "unrent-unrented"); // Remove friends, the owner and renteduntil values getFriendsFeature().clearFriends(); UUID oldRenter = getRenter(); setRenter(null); setRentedUntil(null); setTimesExtended(-1); removeLastActiveTime(); // Notify about updates this.notifyAndUpdate(new UnrentedRegionEvent(this, oldRenter, Math.max(0, moneyBack))); return true; }
3.26
AreaShop_RentRegion_sendExpirationWarnings_rdh
/** * Send the expiration warnings from the selected profile which is specified in the config. * Sends all warnings since previous call until (now + normal delay), delay can be found in the config as well. */ public void sendExpirationWarnings() { // Send from warningsDoneUntil to current+delay if (isDeleted() || (!isRented())) { return;} ConfigurationSection profileSection = getConfigurationSectionSetting("rent.expirationWarningProfile", "expirationWarningProfiles"); if (profileSection == null) {return; } // Check if a warning needs to be send for each defined point in time Player player = Bukkit.getPlayer(getRenter()); long sendUntil = Calendar.getInstance().getTimeInMillis() + ((plugin.getConfig().getInt("expireWarning.delay") * 60) * 1000); for (String timeBefore : profileSection.getKeys(false)) { long timeBeforeParsed = Utils.durationStringToLong(timeBefore);if (timeBeforeParsed <= 0) { return; } long checkTime = getRentedUntil() - timeBeforeParsed; if ((checkTime > warningsDoneUntil) && (checkTime <= sendUntil)) { List<String> commands; if (profileSection.isConfigurationSection(timeBefore)) {/* Legacy config layout: "1 minute": warnPlayer: true commands: ["say hi"] */ commands = profileSection.getStringList(timeBefore + ".commands"); // Warn player if (profileSection.getBoolean(timeBefore + ".warnPlayer") && (player != null)) { message(player, "rent-expireWarning"); } } else { commands = profileSection.getStringList(timeBefore); } this.runCommands(Bukkit.getConsoleSender(), commands); } } warningsDoneUntil = sendUntil; }
3.26
AreaShop_RentRegion_getFormattedPrice_rdh
/** * Get the formatted string of the price (includes prefix and suffix). * * @return The formatted string of the price */ public String getFormattedPrice() { return Utils.formatCurrency(getPrice()); }
3.26
AreaShop_RentRegion_setRentedUntil_rdh
/** * Set the time until the region is rented (milliseconds from 1970, system time). * * @param rentedUntil * The time until the region is rented */public void setRentedUntil(Long rentedUntil) { if (rentedUntil == null) { setSetting("rent.rentedUntil", null); } else {setSetting("rent.rentedUntil", rentedUntil); } }
3.26
AreaShop_RentRegion_getDuration_rdh
/** * Get the duration of 1 rent period. * * @return The duration in milliseconds of 1 rent period */ public long getDuration() { return Utils.durationStringToLong(getDurationString());}
3.26
AreaShop_RentRegion_getPlayerName_rdh
/** * Get the name of the player renting this region. * * @return Name of the player renting this region, if unavailable by UUID it will return the old cached name, if that is unavailable it will return &lt;UNKNOWN&gt; */ public String getPlayerName() { String result = Utils.toName(getRenter()); if ((result == null) || result.isEmpty()) {result = config.getString("rent.renterName"); if ((result == null) || result.isEmpty()) { result = "<UNKNOWN>"; }} return result; }
3.26
AreaShop_RentRegion_getTimesExtended_rdh
/** * Get how many times the rent has already been extended. * * @return The number of times extended */ public int getTimesExtended() { return config.getInt("rent.timesExtended"); }
3.26
AreaShop_RentRegion_getRenter_rdh
/** * Get the UUID of the player renting the region. * * @return The UUID of the renter */ public UUID getRenter() { String renter = config.getString("rent.renter"); if (renter != null) { try { return UUID.fromString(renter); } catch (IllegalArgumentException e) { // Incorrect UUID } } return null; }
3.26
AreaShop_RentRegion_getPrice_rdh
/** * Get the price of the region. * * @return The price of the region */ public double getPrice() { return Math.max(0, Utils.evaluateToDouble(getStringSetting("rent.price"), this)); }
3.26
AreaShop_RentRegion_getMaxRentTime_rdh
/** * Get the maximum time the player can rent the region in advance (milliseconds). * * @return The maximum rent time in milliseconds */ public long getMaxRentTime() { return Utils.getDurationFromMinutesOrStringInput(getStringSetting("rent.maxRentTime")); }
3.26
AreaShop_RentRegion_getInactiveTimeUntilUnrent_rdh
/** * Minutes until automatic unrent when player is offline. * * @return The number of milliseconds until the region is unrented while player is offline */ public long getInactiveTimeUntilUnrent() { return Utils.getDurationFromMinutesOrStringInput(getStringSetting("rent.inactiveTimeUntilUnrent")); }
3.26
AreaShop_RentRegion_setRenter_rdh
/** * Set the renter of this region. * * @param renter * The UUID of the player that should be set as the renter */ public void setRenter(UUID renter) { if (renter == null) { setSetting("rent.renter", null); setSetting("rent.renterName", null); } else { setSetting("rent.renter", renter.toString()); setSetting("rent.renterName", Utils.toName(renter)); } }
3.26
AreaShop_RentRegion_getTimeLeft_rdh
/** * Get the time that is left on the region. * * @return The time left on the region */ public long getTimeLeft() { if (isRented()) { return this.getRentedUntil() - Calendar.getInstance().getTimeInMillis(); } else { return 0; } }
3.26
AreaShop_RentRegion_getRentedUntil_rdh
/** * Get the time until this region is rented (time from 1970 epoch). * * @return The epoch time until which this region is rented */ public long getRentedUntil() { return getLongSetting("rent.rentedUntil"); }
3.26
AreaShop_RentRegion_getDurationString_rdh
/** * Get the duration string, includes 'number indentifier'. * * @return The duration string */ public String getDurationString() { return getStringSetting("rent.duration"); }
3.26
AreaShop_RentRegion_getMoneyBackPercentage_rdh
/** * Get the moneyBack percentage. * * @return The % of money the player will get back when unrenting */public double getMoneyBackPercentage() { return Utils.evaluateToDouble(getStringSetting("rent.moneyBack"), this); }
3.26
AreaShop_RentRegion_setDuration_rdh
/** * Set the duration of the rent. * * @param duration * The duration of the rent (as specified on the documentation pages) */ public void setDuration(String duration) { setSetting("rent.duration", duration); }
3.26
AreaShop_RentRegion_setTimesExtended_rdh
/** * Set the number of times the region has been extended. * * @param times * The number of times the region has been extended */ public void setTimesExtended(int times) { if (times < 0) { setSetting("rent.timesExtended", null); } else { setSetting("rent.timesExtended", times); } }
3.26
AreaShop_RentRegion_rent_rdh
/** * Rent a region. * * @param offlinePlayer * The player that wants to rent the region * @return true if it succeeded and false if not */public boolean rent(OfflinePlayer offlinePlayer) { if (plugin.getEconomy() == null) { message(offlinePlayer, "general-noEconomy"); return false; } // Check if the player has permission if (!plugin.hasPermission(offlinePlayer, "areashop.rent")) { message(offlinePlayer, "rent-noPermission"); return false; } // Check location restrictions if (getWorld() == null) { message(offlinePlayer, "general-noWorld");return false; } if (getRegion() == null) { message(offlinePlayer, "general-noRegion"); return false; } boolean extend = false; if ((getRenter() != null) && offlinePlayer.getUniqueId().equals(getRenter())) { extend = true; } // Check if available or extending if (isRented() && (!extend)) { message(offlinePlayer, "rent-someoneElse"); return false; } // These checks are only relevant for online players doing the renting/buying themselves Player player = offlinePlayer.getPlayer(); if (player != null) { // Check if the players needs to be in the region for renting if (restrictedToRegion() && ((!player.getWorld().getName().equals(getWorldName())) || (!getRegion().contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ())))) { message(offlinePlayer, "rent-restrictedToRegion"); return false;} // Check if the players needs to be in the world for renting if (restrictedToWorld() && (!player.getWorld().getName().equals(getWorldName()))) { message(offlinePlayer, "rent-restrictedToWorld", player.getWorld().getName()); return false; } } // Check region limits if this is not extending if (!(extend && config.getBoolean("allowRegionExtendsWhenAboveLimits"))) { LimitResult limitResult; if (extend) { limitResult = this.limitsAllow(RegionType.RENT, offlinePlayer, true); } else { limitResult = this.limitsAllow(RegionType.RENT, offlinePlayer); } AreaShop.debug("LimitResult: " + limitResult.toString()); if (!limitResult.actionAllowed()) { if (limitResult.getLimitingFactor() == LimitType.TOTAL) {message(offlinePlayer, "total-maximum", limitResult.getMaximum(), limitResult.getCurrent(), limitResult.getLimitingGroup()); return false; } if (limitResult.getLimitingFactor() == LimitType.RENTS) { message(offlinePlayer, "rent-maximum", limitResult.getMaximum(), limitResult.getCurrent(), limitResult.getLimitingGroup()); return false; } if (limitResult.getLimitingFactor() == LimitType.EXTEND) { message(offlinePlayer, "rent-maximumExtend", limitResult.getMaximum(), limitResult.getCurrent() + 1, limitResult.getLimitingGroup()); return false; } return false; } } // Check if the player can still extend this rent if (extend && (!plugin.hasPermission(offlinePlayer, "areashop.rentextendbypass"))) { if ((getMaxExtends() >= 0) && (getTimesExtended() >= getMaxExtends())) { message(offlinePlayer, "rent-maxExtends"); return false; } } // Check if there is enough time left before hitting maxRentTime boolean extendToMax = false; double price = getPrice(); long timeNow = Calendar.getInstance().getTimeInMillis(); long timeRented = 0; long maxRentTime = getMaxRentTime(); if (isRented()) { timeRented = getRentedUntil() - timeNow; } if ((((timeRented + getDuration()) > maxRentTime) && (!plugin.hasPermission(offlinePlayer, "areashop.renttimebypass"))) && (maxRentTime != (-1))) { // Extend to the maximum instead of adding a full period if (getBooleanSetting("rent.extendToFullWhenAboveMaxRentTime")) { if (timeRented >= maxRentTime) { message(offlinePlayer, "rent-alreadyAtFull"); return false;} else { long toRentPart = maxRentTime - timeRented; extendToMax = true; price = (((double) (toRentPart)) / getDuration()) * price; } } else { message(offlinePlayer, "rent-maxRentTime"); return false; } }// Check if the player has enough money if (!plugin.getEconomy().has(offlinePlayer, getWorldName(), price)) { if (extend) { message(offlinePlayer, "rent-lowMoneyExtend", Utils.formatCurrency(plugin.getEconomy().getBalance(offlinePlayer, getWorldName()))); } else { message(offlinePlayer, "rent-lowMoneyRent", Utils.formatCurrency(plugin.getEconomy().getBalance(offlinePlayer, getWorldName()))); } return false; } // Broadcast and check event RentingRegionEvent event = new RentingRegionEvent(this, offlinePlayer, extend); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { message(offlinePlayer, "general-cancelled", event.getReason()); return false;} // Substract the money from the players balance EconomyResponse r = plugin.getEconomy().withdrawPlayer(offlinePlayer, getWorldName(), price); if (!r.transactionSuccess()) { message(offlinePlayer, "rent-payError"); AreaShop.debug((((("Something went wrong with getting money from " + offlinePlayer.getName()) + " while renting ") + getName()) + ": ") + r.errorMessage); return false; } // Optionally give money to the landlord OfflinePlayer landlordPlayer = null; if (getLandlord() != null) { landlordPlayer = Bukkit.getOfflinePlayer(getLandlord()); } String landlordName = getLandlordName(); if (landlordName != null) { if ((landlordPlayer != null) && (landlordPlayer.getName() != null)) {r = plugin.getEconomy().depositPlayer(landlordPlayer, getWorldName(), price); } else { r = plugin.getEconomy().depositPlayer(landlordName, getWorldName(), price);} if ((r == null) || (!r.transactionSuccess())) { AreaShop.warn((((((("Something went wrong with paying '" + landlordName) + "' ") + Utils.formatCurrency(price)) + " for his rent of region ") + getName()) + " to ") + offlinePlayer.getName()); } } // Get the time until the region will be rented Calendar calendar = Calendar.getInstance(); if (extendToMax) { calendar.setTimeInMillis(calendar.getTimeInMillis() + getMaxRentTime()); } else if (extend) { calendar.setTimeInMillis(getRentedUntil() + getDuration()); } else { calendar.setTimeInMillis(calendar.getTimeInMillis() + getDuration()); } // Add values to the rent and send it to FileManager setRentedUntil(calendar.getTimeInMillis()); setRenter(offlinePlayer.getUniqueId()); updateLastActiveTime(); // Fire schematic event and updated times extended if (!extend) { this.handleSchematicEvent(RegionEvent.RENTED); setTimesExtended(0); } else { setTimesExtended(getTimesExtended() + 1); } // Send message to the player if (extendToMax) { message(offlinePlayer, "rent-extendedToMax"); } else if (extend) { message(offlinePlayer, "rent-extended"); } else { message(offlinePlayer, "rent-rented"); } // Notify about updates this.notifyAndUpdate(new RentedRegionEvent(this, extend)); return true; }
3.26
AreaShop_RentRegion_checkExpiration_rdh
/** * Check if the rent should expire. * * @return true if the rent has expired and has been unrented, false otherwise */ public boolean checkExpiration() { long now = Calendar.getInstance().getTimeInMillis(); if (((!isDeleted()) && isRented()) && (now > getRentedUntil())) { // Extend rent if configured for that if (getBooleanSetting("rent.autoExtend") && extend()) { return false; } // Send message to the player if online Player v9 = Bukkit.getPlayer(getRenter()); if (unRent(false, null)) { if (v9 != null) { message(v9, "unrent-expired"); } return true; } } return false;}
3.26
AreaShop_RentRegion_getMaxExtends_rdh
/** * Get the max number of extends of this region. * * @return -1 if infinite otherwise the maximum number */ public int getMaxExtends() { return getIntegerSetting("rent.maxExtends"); }
3.26
AreaShop_RentRegion_setPrice_rdh
/** * Change the price of the region. * * @param price * The price of the region */ public void setPrice(Double price) {setSetting("rent.price", price); }
3.26
AreaShop_RentRegion_isRenter_rdh
/** * Check if a player is the renter of this region. * * @param player * Player to check * @return true if this player rents this region, otherwise false */ public boolean isRenter(Player player) {return (player != null) && isRenter(player.getUniqueId()); }
3.26
AreaShop_FriendsFeature_deleteFriend_rdh
/** * Delete a friend from the region. * * @param player * The UUID of the player to delete * @param by * The CommandSender that is adding the friend, or null * @return true if the friend has been added, false if adding a friend was cancelled by another plugin */ public boolean deleteFriend(UUID player, CommandSender by) {// Fire and check event DeletedFriendEvent event = new DeletedFriendEvent(getRegion(), Bukkit.getOfflinePlayer(player), by); Bukkit.getPluginManager().callEvent(event); if (event.isCancelled()) { plugin.message(by, "general-cancelled", event.getReason(), this); return false; } Set<String> friends = new HashSet<>(getRegion().getConfig().getStringList("general.friends")); friends.remove(player.toString()); List<String> list = new ArrayList<>(friends); if (list.isEmpty()) { getRegion().setSetting("general.friends", null); } else { getRegion().setSetting("general.friends", list); } return true;}
3.26
AreaShop_FriendsFeature_getFriendNames_rdh
/** * Get the list of friends added to this region. * * @return Friends added to this region */ public Set<String> getFriendNames() { HashSet<String> result = new HashSet<>(); for (UUID friend : getFriends()) { OfflinePlayer player = Bukkit.getOfflinePlayer(friend); if ((player != null) && (player.getName() != null)) { result.add(player.getName()); } } return result; }
3.26
AreaShop_FriendsFeature_clearFriends_rdh
/** * Remove all friends that are added to this region. */ public void clearFriends() {getRegion().setSetting("general.friends", null); }
3.26
AreaShop_FriendsFeature_addFriend_rdh
/** * Add a friend to the region. * * @param player * The UUID of the player to add * @param by * The CommandSender that is adding the friend, or null * @return true if the friend has been added, false if adding a friend was cancelled by another plugin */ public boolean addFriend(UUID player, CommandSender by) { // Fire and check event AddedFriendEvent v0 = new AddedFriendEvent(getRegion(), Bukkit.getOfflinePlayer(player), by); Bukkit.getPluginManager().callEvent(v0); if (v0.isCancelled()) { plugin.message(by, "general-cancelled", v0.getReason(), this); return false; } Set<String> friends = new HashSet<>(getRegion().getConfig().getStringList("general.friends")); friends.add(player.toString()); List<String> v2 = new ArrayList<>(friends); getRegion().setSetting("general.friends", v2); return true; }
3.26
AreaShop_FriendsFeature_getFriends_rdh
/** * Get the list of friends added to this region. * * @return Friends added to this region */ public Set<UUID> getFriends() { HashSet<UUID> result = new HashSet<>(); for (String friend : getRegion().getConfig().getStringList("general.friends")) { try { UUID id = UUID.fromString(friend); result.add(id); } catch (IllegalArgumentException e) { // Don't add it } } return result; }
3.26
AreaShop_ImportJob_loadConfiguration_rdh
/** * Load a YamlConfiguration from disk using UTF-8 encoding. * * @param from * File to read the configuration from * @return YamlConfiguration if the file exists and got read wihout problems, otherwise null */ private YamlConfiguration loadConfiguration(File from) { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(from), Charsets.UTF_8)) { return YamlConfiguration.loadConfiguration(reader); } catch (IOException e) { return null; } }
3.26
AreaShop_ImportJob_execute_rdh
/** * Execute the job. */ private void execute() { // Check for RegionForSale data File regionForSaleFolder = new File(f0.getDataFolder().getParentFile().getAbsolutePath(), "RegionForSale"); if (!regionForSaleFolder.exists()) { message("import-noPluginFolder", regionForSaleFolder.getName()); return; } File worldsFolder = new File(regionForSaleFolder.getAbsolutePath(), "worlds"); if (!worldsFolder.exists()) { message("import-noWorldsFolder");return; } File[] worldFolders = worldsFolder.listFiles(); if (worldFolders == null) { message("import-noWorldsFolder"); return; } // Import data for each world message("import-start"); // Group with settings for all imported regions RegionGroup regionForSaleGroup = new RegionGroup(f0, "RegionForSale"); f0.getFileManager().addGroup(regionForSaleGroup); // Import /RegionForSale/config.yml settings File regionForSaleConfigFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml"); YamlConfiguration regionForSaleConfig = loadConfiguration(regionForSaleConfigFile); if (regionForSaleConfig == null) { messageNoPrefix("import-loadConfigFailed", regionForSaleConfigFile.getAbsolutePath()); regionForSaleConfig = new YamlConfiguration(); } else { importRegionSettings(regionForSaleConfig, regionForSaleGroup.getSettings(), null, false); regionForSaleGroup.setSetting("priority", 0); } // Import /RegionForSale/general.yml settings File regionForSaleGeneralFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml"); YamlConfiguration regionForSaleGeneral = loadConfiguration(regionForSaleConfigFile); if (regionForSaleGeneral == null) { messageNoPrefix("import-loadConfigFailed", regionForSaleGeneralFile.getAbsolutePath()); } else { // Collection interval of RegionForSale maps to rent duration String duration = "1 day"; if (regionForSaleGeneral.isLong("interval.collect_money")) {duration = minutesToString(regionForSaleGeneral.getLong("interval.collect_money")); } regionForSaleGroup.setSetting("rent.duration", duration); // Global economy account has an effect close to landlord in AreaShop if (regionForSaleGeneral.isString("global_econ_account")) { regionForSaleGroup.setSetting("general.landlordName", regionForSaleGeneral.getString("global_econ_account")); } } regionForSaleGroup.saveRequired(); // //////// Handle defaults of RegionForSale // Set autoExtend, to keep the same behavior as RegionForSale had regionForSaleGroup.setSetting("rent.autoExtend", true); // Import regions from each world for (File worldFolder : worldFolders) { // Skip files if ((!worldFolder.isDirectory()) || worldFolder.isHidden()) { continue; } messageNoPrefix("import-doWorld", worldFolder.getName()); // Get the Bukkit world World world = Bukkit.getWorld(worldFolder.getName()); if (world == null) { messageNoPrefix("import-noBukkitWorld"); continue; } // Get the WorldGuard RegionManager RegionManager regionManager = f0.getRegionManager(world); if (regionManager == null) { messageNoPrefix("import-noRegionManger"); continue; } // Load the /worlds/<world>/regions.yml file File regionsFile = new File(worldFolder.getAbsolutePath(), "regions.yml"); YamlConfiguration regions = loadConfiguration(regionsFile); if (regions == null) { messageNoPrefix("import-loadRegionsFailed", regionsFile.getAbsolutePath()); continue; } // Load /worlds/<world>/config.yml file File worldConfigFile = new File(worldFolder.getAbsolutePath(), "config.yml"); YamlConfiguration worldConfig = loadConfiguration(worldConfigFile); if (worldConfig == null) { messageNoPrefix("import-loadWorldConfigFailed", worldConfigFile.getAbsolutePath()); // Simply skip importing the settings, since this is not really fatal worldConfig = new YamlConfiguration(); } else { // RegionGroup with all world settings RegionGroup worldGroup = new RegionGroup(f0, "RegionForSale-" + worldFolder.getName()); importRegionSettings(worldConfig, worldGroup.getSettings(), null, false); worldGroup.setSetting("priority", 1); worldGroup.addWorld(worldFolder.getName()); f0.getFileManager().addGroup(regionForSaleGroup); worldGroup.saveRequired(); } // Create groups to hold settings of /worlds/<world>/parent-regions.yml File parentRegionsFile = new File(worldFolder.getAbsolutePath(), "parent-regions.yml"); YamlConfiguration parentRegions = loadConfiguration(parentRegionsFile); if (parentRegions == null) { messageNoPrefix("import-loadParentRegionsFailed", parentRegionsFile.getAbsolutePath());// Non-fatal, so just continue } else { for (String parentRegionName : parentRegions.getKeys(false)) { // Get WorldGuard region ProtectedRegion worldGuardRegion = regionManager.getRegion(parentRegionName); if (worldGuardRegion == null) { messageNoPrefix("import-noWorldGuardRegionParent", parentRegionName); continue; } // Get settings section ConfigurationSection parentRegionSection = parentRegions.getConfigurationSection(parentRegionName); if (parentRegionSection == null) { messageNoPrefix("import-improperParentRegion", parentRegionName); continue; }// Skip if it does not have any settings if (parentRegionSection.getKeys(false).isEmpty()) { continue; } // Import parent region settings into a RegionGroup RegionGroup parentRegionGroup = new RegionGroup(f0, (("RegionForSale-" + worldFolder.getName()) + "-") + parentRegionName); importRegionSettings(parentRegionSection, parentRegionGroup.getSettings(), null, false); parentRegionGroup.setSetting("priority", 2 + parentRegionSection.getLong("info.priority", 0)); parentRegionGroup.saveRequired(); // TODO add all regions that are contained in this parent region // Utils.getWorldEditRegionsInSelection() }} // Read and import regions for (String regionKey : regions.getKeys(false)) {GeneralRegion existingRegion = f0.getFileManager().getRegion(regionKey); if (existingRegion != null) { if (world.getName().equalsIgnoreCase(existingRegion.getWorldName())) { messageNoPrefix("import-alreadyAdded", regionKey); } else { messageNoPrefix("import-alreadyAddedOtherWorld", regionKey, existingRegion.getWorldName(), world.getName()); } continue; } ConfigurationSection regionSection = regions.getConfigurationSection(regionKey); if (regionSection == null) { messageNoPrefix("import-invalidRegionSection", regionKey); continue;} // Get WorldGuard region ProtectedRegion worldGuardRegion = regionManager.getRegion(regionKey); if (worldGuardRegion == null) { messageNoPrefix("import-noWorldGuardRegion", regionKey); continue; } String owner = regionSection.getString("info.owner", null); boolean isBought = regionSection.getBoolean("info.is-bought"); // TODO: should also take into config settings of parent regions boolean rentable = regionSection.getBoolean("economic-settings.rentable", worldConfig.getBoolean("economic-settings.rentable", regionForSaleConfig.getBoolean("economic-settings.rentable")));boolean buyable = regionSection.getBoolean("economic-settings.buyable", worldConfig.getBoolean("economic-settings.buyable", regionForSaleConfig.getBoolean("economic-settings.buyable"))); // Can be bought and rented, import as buy if (buyable && rentable) { messageNoPrefix("import-buyAndRent", regionKey); } // Cannot be bought or rented, skip if (((!buyable) && (!rentable)) && (owner == null)) { messageNoPrefix("import-noBuyAndNoRent", regionKey);continue; } // Create region GeneralRegion region; if (rentable || ((owner != null) && (!isBought))) { region = new RentRegion(regionKey, world); } else { region = new BuyRegion(regionKey, world); } AddingRegionEvent event = f0.getFileManager().addRegion(region); if (event.isCancelled()) { messageNoPrefix("general-cancelled", event.getReason()); continue; } // Import settings importRegionSettings(regionSection, region.getConfig(), region, (!buyable) && (!rentable)); region.getConfig().set("general.importedFrom", "RegionForSale"); // Get existing owners and members List<UUID> existing = new ArrayList<>(); if (owner != null) { @SuppressWarnings("deprecation") OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(owner);if (offlinePlayer != null) { existing.add(offlinePlayer.getUniqueId()); } } for (UUID uuid : f0.getWorldGuardHandler().getOwners(worldGuardRegion).asUniqueIdList()) { if (!existing.contains(uuid)) { existing.add(uuid); } } for (UUID uuid : f0.getWorldGuardHandler().getMembers(worldGuardRegion).asUniqueIdList()) { if (!existing.contains(uuid)) { existing.add(uuid); } }// First owner (or if none, the first member) will be the renter/buyer if (!existing.isEmpty()) { region.setOwner(existing.remove(0)); } // Add others as friends for (UUID friend : existing) { region.getFriendsFeature().addFriend(friend, null); } region.saveRequired(); messageNoPrefix("import-imported", regionKey); } } // Update all regions f0.getFileManager().updateAllRegions(sender);// Write all imported regions and settings to disk f0.getFileManager().saveRequiredFiles(); }
3.26
AreaShop_ImportJob_messageNoPrefix_rdh
/** * Send a message to a target without a prefix. * * @param key * The key of the language string * @param replacements * The replacements to insert in the message */ public void messageNoPrefix(String key, Object... replacements) { f0.messageNoPrefix(sender, key, replacements); if (!(sender instanceof ConsoleCommandSender)) { f0.messageNoPrefix(Bukkit.getConsoleSender(), key, replacements); } }
3.26
AreaShop_ImportJob_message_rdh
/** * Send a message to a target, prefixed by the default chat prefix. * * @param key * The key of the language string * @param replacements * The replacements to insert in the message */ public void message(String key, Object... replacements) {f0.message(sender, key, replacements); if (!(sender instanceof ConsoleCommandSender)) { f0.message(Bukkit.getConsoleSender(), key, replacements); } }
3.26
AreaShop_ImportJob_importRegionSettings_rdh
/** * Import region specific settings from a RegionForSale source to an AreaShop target ConfigurationSection. * * @param from * RegionForSale config section that specifies region settings * @param to * AreaShop config section that specifies region settings * @param region * GeneralRegion to copy settings to, or null if doing generic settings * @param permanent * Region cannot be rented or bought, disables some features */ private void importRegionSettings(ConfigurationSection from, ConfigurationSection to, GeneralRegion region, boolean permanent) { // Maximum rental time, TODO check if this is actually the same if (from.isLong("permissions.max-rent-time")) { to.set("rent.maxRentTime", minutesToString(from.getLong("permissions.max-rent-time"))); } // Region rebuild if (from.getBoolean("region-rebuilding.auto-rebuild")) { to.set("general.enableRestore", true); } // Get price settings String unit = from.getString("economic-settings.unit-type"); String rentPrice = from.getString("economic-settings.cost-per-unit.rent");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"); // Determine unit and add that to the price String unitSuffix = ""; if ("region".equalsIgnoreCase(unit)) { // add nothing } else if ("m3".equalsIgnoreCase(unit)) { unitSuffix = "*%volume%"; } else { // m2 or nothing (in case not set, we should actually look in parent files to correctly set this...) unitSuffix = "*(%volume%/%height%)";// This is better than width*depth because of polygon regions } // Apply settings if (rentPrice != null) { to.set("rent.price", rentPrice + unitSuffix); } if (buyPrice != null) { to.set("buy.price", buyPrice + unitSuffix); if (sellPrice != null) { try { double buyPriceAmount = Double.parseDouble(buyPrice);double sellPriceAmount = Double.parseDouble(sellPrice); to.set("buy.moneyBack", (sellPriceAmount / buyPriceAmount) * 100); } catch (NumberFormatException e) { // There is not always a region here for the message, should probably indicate something though message("import-moneyBackFailed", buyPrice, sellPrice); }} } // Apply permanent region settings if (permanent) { to.set("buy.resellDisabled", true); to.set("buy.sellDisabled", true); to.set("general.countForLimits", false); } // Set rented until if (from.isLong("info.last-withdrawal") && (region instanceof RentRegion)) { RentRegion rentRegion = ((RentRegion) (region)); long lastWithdrawal = from.getLong("info.last-withdrawal"); // Because the rental duration is already imported into the region and its parents this should be correct rentRegion.setRentedUntil(lastWithdrawal + rentRegion.getDuration()); } // Import signs (list of strings like "297, 71, -22") if (from.isList("info.signs") && (region != null)) { for (String signLocation : from.getStringList("info.signs")) { String[] locationParts = signLocation.split(", "); if (locationParts.length != 3) { message("import-invalidSignLocation", region.getName(), signLocation); continue; } // Parse the location Location location; try { location = new Location(region.getWorld(), Double.parseDouble(locationParts[0]), Double.parseDouble(locationParts[1]), Double.parseDouble(locationParts[2])); } catch (NumberFormatException e) { message("import-invalidSignLocation", region.getName(), signLocation); continue; } // Check if this location is already added to a region RegionSign v51 = SignsFeature.getSignByLocation(location); if (v51 != null) { if (!v51.getRegion().equals(region)) { message("import-signAlreadyAdded", region.getName(), signLocation, v51.getRegion().getName()); } continue;} // SignType and Facing will be written when the sign is updated later region.getSignsFeature().addSign(location, null, null, null); } } }
3.26
AreaShop_ImportJob_minutesToString_rdh
/** * Convert minutes to a human-readable string. * * @param minutes * Value to convert * @return String that represents the same length of time in a readable format, like "1 day", "5 minutes", "3 months" */ private String minutesToString(long minutes) { // If the specified number of minutes can map nicely to a higher unit, use that one String resultUnit = "minute"; long resultValue = minutes; for (TimeUnit unit : timeUnitLookup) { long result = minutes / unit.minutes; if ((resultValue * unit.minutes) == minutes) { resultUnit = unit.identifier; resultValue = result; break; } } return ((resultValue + " ") + resultUnit) + (resultValue == 1 ? "" : "s"); }
3.26
AreaShop_RegionFeature_listen_rdh
/** * Start listening to events. */ public void listen() { plugin.getServer().getPluginManager().registerEvents(this, plugin); }
3.26
AreaShop_RegionFeature_setRegion_rdh
/** * Set the region for this feature. * * @param region * Feature region */ public void setRegion(GeneralRegion region) { this.region = region; }
3.26
AreaShop_RegionFeature_getRegion_rdh
/** * Get the region of this feature. * * @return region of this feature, or null if generic */ public GeneralRegion getRegion() { return region; }
3.26
AreaShop_RegionFeature_shutdownFeature_rdh
/** * Destroy the feature and deregister everything. */public void shutdownFeature() { HandlerList.unregisterAll(this); shutdown();}
3.26
AreaShop_ImportCommand_execute_rdh
// TODO: // - Landlord? // - Friends // - Region flags? // - Settings from the 'permissions' section in RegionForSale/config.yml? @Override public void execute(CommandSender sender, String[] args) { if (!sender.hasPermission("areashop.import")) { plugin.message(sender, "import-noPermission"); return; } if (args.length < 2) { plugin.message(sender, "import-help"); return; } if (!"RegionForSale".equalsIgnoreCase(args[1])) { plugin.message(sender, "import-wrongSource"); return; } if (!confirm(sender, args, Message.fromKey("import-confirm"))) { return; } new ImportJob(sender); }
3.26
AreaShop_WorldEditSelection_getMaximumLocation_rdh
/** * Get the maximum Location of the selection. * * @return Location with the highest x, y and z */ public Location getMaximumLocation() { return maximum;}
3.26
AreaShop_WorldEditSelection_getWidth_rdh
/** * Get X-size. * * @return width */ public int getWidth() { return (maximum.getBlockX() - minimum.getBlockX()) + 1;}
3.26
AreaShop_WorldEditSelection_getMinimumLocation_rdh
/** * Get the minimum Location of the selection. * * @return Location with the lowest x, y and z */ public Location getMinimumLocation() { return minimum; }
3.26
AreaShop_WorldEditSelection_getLength_rdh
/** * Get Z-size. * * @return length */ public int getLength() { return (maximum.getBlockZ() - minimum.getBlockZ()) + 1; }
3.26
AreaShop_WorldGuardHandler7_beta_1_buildDomain_rdh
/** * Build a DefaultDomain from a RegionAccessSet. * * @param regionAccessSet * RegionAccessSet to read * @return DefaultDomain containing the entities from the RegionAccessSet */ private DefaultDomain buildDomain(RegionAccessSet regionAccessSet) { DefaultDomain owners = new DefaultDomain(); for (String playerName : regionAccessSet.getPlayerNames()) { owners.addPlayer(playerName); }for (UUID uuid : regionAccessSet.getPlayerUniqueIds()) { owners.addPlayer(uuid);} for (String group : regionAccessSet.getGroupNames()) { owners.addGroup(group); } return owners; }
3.26
AreaShop_SellCommand_canUse_rdh
/** * Check if a person can sell the region. * * @param person * The person to check * @param region * The region to check for * @return true if the person can sell it, otherwise false */ public static boolean canUse(CommandSender person, GeneralRegion region) { if (person.hasPermission("areashop.sell")) { return true; } if (person instanceof Player) { Player player = ((Player) (person)); return region.isOwner(player) && person.hasPermission("areashop.sellown"); } return false; }
3.26
AreaShop_SignLinkerManager_isInSignLinkMode_rdh
/** * Check if the player is in sign linking mode. * * @param player * The player to check * @return true if the player is in sign linking mode, otherwise false */ public boolean isInSignLinkMode(Player player) { return signLinkers.containsKey(player.getUniqueId()); }
3.26
AreaShop_SignLinkerManager_enterSignLinkMode_rdh
/** * Let a player enter sign linking mode. * * @param player * The player that has to enter sign linking mode * @param profile * The profile to use for the signs (null for default) */ public void enterSignLinkMode(Player player, String profile) { signLinkers.put(player.getUniqueId(), new SignLinker(player, profile)); plugin.message(player, "linksigns-first"); plugin.message(player, "linksigns-next"); if (!eventsRegistered) { eventsRegistered = true; plugin.getServer().getPluginManager().registerEvents(this, plugin); } }
3.26
AreaShop_SignLinkerManager_exitSignLinkMode_rdh
/** * Let a player exit sign linking mode. * * @param player * The player that has to exit sign linking mode */ public void exitSignLinkMode(Player player) { signLinkers.remove(player.getUniqueId()); if (eventsRegistered && signLinkers.isEmpty()) { eventsRegistered = false; HandlerList.unregisterAll(this); } plugin.message(player, "linksigns-stopped");}
3.26
AreaShop_SignLinkerManager_onPlayerInteract_rdh
/** * On player interactions. * * @param event * The PlayerInteractEvent */ @EventHandler(priority = EventPriority.HIGH) public void onPlayerInteract(PlayerInteractEvent event) { if (isInSignLinkMode(event.getPlayer())) { event.setCancelled(true); Player player = event.getPlayer(); SignLinker linker = signLinkers.get(event.getPlayer().getUniqueId()); if ((event.getAction() == Action.RIGHT_CLICK_AIR) || (event.getAction() == Action.RIGHT_CLICK_BLOCK)) { // Get the region BlockIterator blockIterator = new BlockIterator(player, 100); while (blockIterator.hasNext()) { Block next = blockIterator.next(); List<GeneralRegion> regions = Utils.getRegions(next.getLocation()); if (regions.size() == 1) { linker.setRegion(regions.get(0)); return; } else if (regions.size() > 1) { Set<String> names = new HashSet<>(); for (GeneralRegion region : regions) { names.add(region.getName()); } plugin.message(player, "linksigns-multipleRegions", Utils.createCommaSeparatedList(names)); plugin.message(player, "linksigns-multipleRegionsAdvice"); return; } } // No regions found within the maximum range plugin.message(player, "linksigns-noRegions"); } else if ((event.getAction() == Action.LEFT_CLICK_AIR) || (event.getAction() == Action.LEFT_CLICK_BLOCK)) { Block block = null; BlockIterator blockIterator = new BlockIterator(player, 100); while (blockIterator.hasNext() && (block == null)) { Block next = blockIterator.next(); if (next.getType() != Material.AIR) { block = next; } } if ((block == null) || (!Materials.isSign(block.getType()))) { plugin.message(player, "linksigns-noSign"); return; } RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation()); if (regionSign != null) { plugin.message(player, "linksigns-alreadyRegistered", regionSign.getRegion()); return; } linker.setSign(block.getLocation(), block.getType(), plugin.getBukkitHandler().getSignFacing(block));}} }
3.26
AreaShop_UnrentedRegionEvent_getRefundedMoney_rdh
/** * Get the amount that is paid back to the player. * * @return The amount of money paid back to the player */ public double getRefundedMoney() { return refundedMoney; }
3.26
AreaShop_UnrentedRegionEvent_getOldRenter_rdh
/** * Get the player that the region was unrented for. * * @return The UUID of the player that the region was unrented for */ public UUID getOldRenter() { return oldRenter; }
3.26
AreaShop_BukkitHandler1_13_getSignFacing_rdh
// Uses BlockData, which does not yet exist in 1.12- @Override public BlockFace getSignFacing(Block block) {if (block == null) { return null; } BlockState blockState = block.getState(); if (blockState == null) {return null; } BlockData blockData = blockState.getBlockData(); if (blockData == null) { return null; } if (blockData instanceof WallSign) { return ((WallSign) (blockData)).getFacing(); } else if (blockData instanceof Sign) { return ((Sign) (blockData)).getRotation(); } return null; }
3.26
AreaShop_BukkitHandler1_13_setSignFacing_rdh
// Uses BlockData, WallSign and Sign which don't exist in 1.12- @Override public boolean setSignFacing(Block block, BlockFace facing) { if ((block == null) || (facing == null)) { return false; } BlockState blockState = block.getState(); if (blockState == null) { return false; } BlockData blockData = blockState.getBlockData(); if (blockData == null) { return false; } if (blockData instanceof WallSign) { ((WallSign) (blockData)).setFacing(facing); } else if (blockData instanceof Sign) { ((Sign) (blockData)).setRotation(facing); } else { return false; } block.setBlockData(blockData); return true; }
3.26
AreaShop_RegionSign_getLocation_rdh
/** * Get the location of this sign. * * @return The location of this sign */ public Location getLocation() { return Utils.configToLocation(getRegion().getConfig().getConfigurationSection(("general.signs." + key) + ".location")); }
3.26
AreaShop_RegionSign_getStringChunk_rdh
/** * Chunk string to be used as key in maps. * * @return Chunk string */ public String getStringChunk() { return SignsFeature.chunkToString(getLocation()); }
3.26
AreaShop_RegionSign_update_rdh
/** * Update this sign. * * @return true if the update was successful, otherwise false */ public boolean update() { // Ignore updates of signs in chunks that are not loaded Location signLocation = getLocation(); if (((signLocation == null) || (signLocation.getWorld() == null)) || (!signLocation.getWorld().isChunkLoaded(signLocation.getBlockX() >> 4, signLocation.getBlockZ() >> 4))) { return false; } if (getRegion().isDeleted()) { return false; } YamlConfiguration regionConfig = getRegion().getConfig(); ConfigurationSection signConfig = getProfile(); Block block = signLocation.getBlock(); if ((signConfig == null) || (!signConfig.isSet(getRegion().getState().getValue()))) { block.setType(Material.AIR); return true; } ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue()); // Get the lines String[] signLines = new String[4]; boolean signEmpty = true; for (int i = 0; i < 4; i++) { signLines[i] = stateConfig.getString("line" + (i + 1)); signEmpty &= (signLines[i] == null) || signLines[i].isEmpty(); } if (signEmpty) { block.setType(Material.AIR); return true; } // Place the sign back (with proper rotation and type) after it has been hidden or (indirectly) destroyed if (!Materials.isSign(block.getType())) { Material signType = getMaterial(); // Don't do physics here, we first need to update the direction block.setType(signType, false); // This triggers a physics update, which pops the sign if not attached properly if (!AreaShop.getInstance().getBukkitHandler().setSignFacing(block, getFacing())) { AreaShop.warn("Failed to update the facing direction of the sign at", getStringLocation(), "to ", getFacing(), ", region:", getRegion().getName()); } // Check if the sign has popped if (!Materials.isSign(block.getType())) { AreaShop.warn("Setting sign", key, "of region", getRegion().getName(), "failed, could not set sign block back"); return false; }} // Save current rotation and type if (!regionConfig.isString(("general.signs." + key) + ".signType")) { getRegion().setSetting(("general.signs." + key) + ".signType", block.getType().name()); } if (!regionConfig.isString(("general.signs." + key) + ".facing")) { BlockFace signFacing = AreaShop.getInstance().getBukkitHandler().getSignFacing(block); getRegion().setSetting(("general.signs." + key) + ".facing", signFacing == null ? null : signFacing.toString()); } // Apply replacements and color and then set it on the sign Sign signState = ((Sign) (block.getState())); for (int i = 0; i < signLines.length; i++) { if (signLines[i] == null) { signState.setLine(i, ""); continue; } signLines[i] = Message.fromString(signLines[i]).replacements(getRegion()).getSingle(); signLines[i] = Utils.applyColors(signLines[i]); signState.setLine(i, signLines[i]); } signState.update(); return true; }
3.26
AreaShop_RegionSign_needsPeriodicUpdate_rdh
/** * Check if the sign needs to update periodically. * * @return true if it needs periodic updates, otherwise false */public boolean needsPeriodicUpdate() { ConfigurationSection signConfig = getProfile(); if ((signConfig == null) || (!signConfig.isSet(getRegion().getState().getValue().toLowerCase()))) { return false; } ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase()); if (stateConfig == null) { return false; } // Check the lines for the timeleft tag for (int i = 1; i <= 4; i++) { String line = stateConfig.getString("line" + i); if (((line != null) && (!line.isEmpty())) && line.contains((Message.VARIABLE_START + AreaShop.tagTimeLeft) + Message.VARIABLE_END)) { return true; } } return false; }
3.26
AreaShop_RegionSign_getFacing_rdh
/** * Get the facing of the sign as saved in the config. * * @return BlockFace the sign faces, or null if unknown */ public BlockFace getFacing() { try { return BlockFace.valueOf(getRegion().getConfig().getString(("general.signs." + key) + ".facing")); } catch (NullPointerException | IllegalArgumentException e) { return null; } }
3.26
AreaShop_RegionSign_getRegion_rdh
/** * Get the region this sign is linked to. * * @return The region this sign is linked to */ public GeneralRegion getRegion() { return signsFeature.getRegion(); }
3.26
AreaShop_RegionSign_getMaterial_rdh
/** * Get the material of the sign as saved in the config. * * @return Material of the sign, usually {@link Material#WALL_SIGN}, {@link Material#SIGN}, or one of the other wood types (different result for 1.13-), Material.AIR if none. */ public Material getMaterial() { String name = getRegion().getConfig().getString(("general.signs." + key) + ".signType"); Material result = Materials.signNameToMaterial(name); return result == null ? Material.AIR : result; }
3.26
AreaShop_RegionSign_getStringLocation_rdh
/** * Location string to be used as key in maps. * * @return Location string */ public String getStringLocation() { return SignsFeature.locationToString(getLocation()); }
3.26
AreaShop_RegionSign_m0_rdh
/** * Remove this sign from the region. */ public void m0() { getLocation().getBlock().setType(Material.AIR); signsFeature.getSignsRef().remove(getStringLocation()); SignsFeature.getAllSigns().remove(getStringLocation()); SignsFeature.getSignsByChunk().get(getStringChunk()).remove(this); getRegion().setSetting("general.signs." + key, null); }
3.26
AreaShop_RegionSign_runSignCommands_rdh
/** * Run commands when a player clicks a sign. * * @param clicker * The player that clicked the sign * @param clickType * The type of clicking * @return true if the commands ran successfully, false if any of them failed */ public boolean runSignCommands(Player clicker, GeneralRegion.ClickType clickType) { ConfigurationSection signConfig = getProfile(); if (signConfig == null) { return false; } ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue().toLowerCase()); // Run player commands if specified List<String> playerCommands = new ArrayList<>(); for (String command : stateConfig.getStringList(clickType.getValue() + "Player")) { // TODO move variable checking code to InteractiveMessenger? playerCommands.add(command.replace((Message.VARIABLE_START + AreaShop.tagClicker) + Message.VARIABLE_END, clicker.getName())); } getRegion().runCommands(clicker, playerCommands);// Run console commands if specified List<String> consoleCommands = new ArrayList<>(); for (String command : stateConfig.getStringList(clickType.getValue() + "Console")) { consoleCommands.add(command.replace((Message.VARIABLE_START + AreaShop.tagClicker) + Message.VARIABLE_END, clicker.getName())); } getRegion().runCommands(Bukkit.getConsoleSender(), consoleCommands); return (!playerCommands.isEmpty()) || (!consoleCommands.isEmpty()); }
3.26
AreaShop_RegionSign_getProfile_rdh
/** * Get the ConfigurationSection defining the sign layout. * * @return The sign layout config */ public ConfigurationSection getProfile() { return getRegion().getConfigurationSectionSetting("general.signProfile", "signProfiles", getRegion().getConfig().get(("general.signs." + key) + ".profile")); }
3.26
AreaShop_SetteleportCommand_canUse_rdh
/** * Check if a person can set the teleport location of the region. * * @param person * The person to check * @param region * The region to check for * @return true if the person can set the teleport location, otherwise false */ public static boolean canUse(CommandSender person, GeneralRegion region) { if (!(person instanceof Player)) { return false; }Player player = ((Player) (person)); return player.hasPermission("areashop.setteleportall") || (region.isOwner(player) && player.hasPermission("areashop.setteleport")); }
3.26
AreaShop_RegionGroup_isMember_rdh
/** * Check if a region is member of the group. * * @param region * Region to check * @return true if the region is in the group, otherwise false */ public boolean isMember(GeneralRegion region) { return getMembers().contains(region.getName()); }
3.26
AreaShop_RegionGroup_getPriority_rdh
/** * Get the priority of the group (higher overwrites). * * @return The priority of the group */ public int getPriority() { return getSettings().getInt("priority"); }
3.26
AreaShop_RegionGroup_m0_rdh
/** * Mark that automatically added regions should be regenerated. */ public void m0() { autoDirty = true; }
3.26
AreaShop_RegionGroup_removeMember_rdh
/** * Remove a member from the group. * * @param region * The region to remove * @return true if the region was in the group before, otherwise false */ public boolean removeMember(GeneralRegion region) { if (regions.remove(region.getName())) { setSetting("regions", new ArrayList<>(regions)); saveRequired(); return true; } return false; }
3.26
AreaShop_RegionGroup_getSettings_rdh
/** * Get the configurationsection with the settings of this group. * * @return The ConfigurationSection with the settings of the group */ public ConfigurationSection getSettings() { ConfigurationSection result = plugin.getFileManager().getGroupSettings(name); if (result != null) { return result; } else { return new YamlConfiguration(); } }
3.26
AreaShop_RegionGroup_addMember_rdh
/** * Adds a member to a group. * * @param region * The region to add to the group (GeneralRegion or a subclass of it) * @return true if the region was not already added, otherwise false */ public boolean addMember(GeneralRegion region) { if (regions.add(region.getName())) { setSetting("regions", new ArrayList<>(regions)); saveRequired(); return true; }return false; }
3.26
AreaShop_RegionGroup_removeWorld_rdh
/** * Remove a member from the group. * * @param world * World to remove * @return true if the region was in the group before, otherwise false */public boolean removeWorld(String world) { if (worlds.remove(world)) { setSetting("regionsFromWorlds", new ArrayList<>(worlds)); saveRequired(); m0(); return true; } return false;}
3.26
AreaShop_RegionGroup_saveRequired_rdh
/** * Indicates this file needs to be saved, will actually get saved later by a task. */ public void saveRequired() { plugin.getFileManager().saveGroupsIsRequired(); }
3.26
AreaShop_RegionGroup_saveNow_rdh
/** * Save the groups to disk now, normally saveRequired() is preferred because of performance. */ public void saveNow() { plugin.getFileManager().saveGroupsNow(); }
3.26
AreaShop_RegionGroup_getMembers_rdh
/** * Get all members of the group. * * @return A list with the names of all members of the group (immutable) */ public Set<String> getMembers() { HashSet<String> result = new HashSet<>(regions); result.addAll(getAutoRegions()); return result; }
3.26
AreaShop_RegionGroup_setSetting_rdh
/** * Set a setting of this group. * * @param path * The path to set * @param setting * The value to set */ public void setSetting(String path, Object setting) { plugin.getFileManager().setGroupSetting(this, path, setting); }
3.26
AreaShop_RegionGroup_addWorld_rdh
/** * Adds a world from which all regions should be added to the group. * * @param world * World from which all regions should be added * @return true if the region was not already added, otherwise false */ public boolean addWorld(String world) { if (worlds.add(world)) { setSetting("regionsFromWorlds", new ArrayList<>(worlds)); saveRequired(); m0(); return true; } return false; }
3.26
AreaShop_RegionGroup_getAutoRegions_rdh
/** * Get automatically added regions. * * @return Set of regions automatically added by the configuration */ public Set<String> getAutoRegions() { if (autoDirty) { autoRegions = new HashSet<>(); for (GeneralRegion region : plugin.getFileManager().getRegions()) { if (worlds.contains(region.getWorldName())) { autoRegions.add(region.getName()); } } autoDirty = false; } return autoRegions; }
3.26
AreaShop_RegionGroup_getWorlds_rdh
/** * Get all worlds from which regions are added automatically. * * @return A list with the names of all worlds (immutable) */public Set<String> getWorlds() { return new HashSet<>(worlds); }
3.26
AreaShop_RegionGroup_getName_rdh
/** * Get the name of the group. * * @return The name of the group */ public String getName() { return name; }
3.26
AreaShop_RegionGroup_getLowerCaseName_rdh
/** * Get the lowercase name of the group (used for getting the config etc). * * @return The name of the group in lowercase */ public String getLowerCaseName() { return getName().toLowerCase(); }
3.26
AreaShop_Analytics_start_rdh
/** * Start analytics tracking. */ public static void start() { // bStats statistics try { Metrics metrics = new Metrics(AreaShop.getInstance()); // Number of regions metrics.addCustomChart(new Metrics.SingleLineChart("region_count") { @Override public int getValue() { return AreaShop.getInstance().getFileManager().getRegions().size(); } }); // Number of rental regions metrics.addCustomChart(new Metrics.SingleLineChart("rental_region_count") { @Override public int getValue() { return AreaShop.getInstance().getFileManager().getRents().size(); } }); // Number of buy regions metrics.addCustomChart(new Metrics.SingleLineChart("buy_region_count") { @Override public int getValue() { return AreaShop.getInstance().getFileManager().getBuys().size(); } }); // Language metrics.addCustomChart(new Metrics.SimplePie("language") { @Override public String getValue() { return AreaShop.getInstance().getConfig().getString("language"); } }); // Pie with region states metrics.addCustomChart(new Metrics.AdvancedPie("region_state") { @Override public HashMap<String, Integer> getValues(HashMap<String, Integer> result) { RegionStateStats stats = getStateStats(); result.put("For Rent", stats.forrent); result.put("Rented", stats.rented); result.put("For Sale", stats.forsale); result.put("Sold", stats.sold); result.put("Reselling", stats.reselling); return result; } }); // Time series of each region state metrics.addCustomChart(new Metrics.SingleLineChart("forrent_region_count") { @Override public int getValue() { return getStateStats().forrent; } }); metrics.addCustomChart(new Metrics.SingleLineChart("rented_region_count") { @Override public int getValue() { return getStateStats().rented;} }); metrics.addCustomChart(new Metrics.SingleLineChart("forsale_region_count") { @Override public int getValue() { return getStateStats().forsale; } }); metrics.addCustomChart(new Metrics.SingleLineChart("sold_region_count") {@Override public int getValue() { return getStateStats().sold; } }); metrics.addCustomChart(new Metrics.SingleLineChart("reselling_region_count") { @Override public int getValue() {return getStateStats().reselling; }}); // TODO track rent/buy/unrent/sell/resell actions (so that it can be reported per collection interval) AreaShop.debug("Started bstats.org statistics service"); } catch (Exception e) { AreaShop.debug("Could not start bstats.org statistics service"); } }
3.26
AreaShop_WorldGuardHandler5_buildDomain_rdh
/** * Build a DefaultDomain from a RegionAccessSet. * * @param regionAccessSet * RegionAccessSet to read * @return DefaultDomain containing the entities from the RegionAccessSet */ private DefaultDomain buildDomain(RegionAccessSet regionAccessSet) { DefaultDomain owners = new DefaultDomain(); for (String playerName : regionAccessSet.getPlayerNames()) { owners.addPlayer(playerName); } // Add by name since UUIDs were not yet supported for (UUID uuid : regionAccessSet.getPlayerUniqueIds()) { OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); if ((offlinePlayer != null) && (offlinePlayer.getName() != null)) { owners.addPlayer(offlinePlayer.getName()); } } for (String group : regionAccessSet.getGroupNames()) { owners.addGroup(group); } return owners; }
3.26
AreaShop_DeletedFriendEvent_getBy_rdh
/** * Get the CommandSender that is adding the friend. * * @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender) */ public CommandSender getBy() { return by; }
3.26
AreaShop_DeletedFriendEvent_getFriend_rdh
/** * Get the OfflinePlayer that is getting added as friend. * * @return The friend that is getting added */ public OfflinePlayer getFriend() { return friend; }
3.26
AreaShop_FastAsyncWorldEditWorldGuardHandler_buildDomain_rdh
/** * Build a DefaultDomain from a RegionAccessSet. * * @param regionAccessSet * RegionAccessSet to read * @return DefaultDomain containing the entities from the RegionAccessSet */ private DefaultDomain buildDomain(RegionAccessSet regionAccessSet) { DefaultDomain owners = new DefaultDomain(); for (String playerName : regionAccessSet.getPlayerNames()) { owners.addPlayer(playerName); } for (UUID uuid : regionAccessSet.getPlayerUniqueIds()) { owners.addPlayer(uuid); }for (String group : regionAccessSet.getGroupNames()) { owners.addGroup(group); } return owners; }
3.26
AreaShop_CommandAreaShop_canExecute_rdh
/** * Check if this Command instance can execute the given command and arguments. * * @param command * The command to check for execution * @param args * The arguments to check * @return true if it can execute the command, false otherwise */ public boolean canExecute(Command command, String[] args) { String commandString = (command.getName() + " ") + StringUtils.join(args, " "); if (commandString.length() > getCommandStart().length()) { return commandString.toLowerCase().startsWith(getCommandStart().toLowerCase() + " "); } return commandString.toLowerCase().startsWith(getCommandStart().toLowerCase()); }
3.26
AreaShop_CommandAreaShop_confirm_rdh
/** * Confirm a command. * * @param sender * To confirm it for, or send a message to confirm * @param args * Command args * @param message * Message to send when confirmation is required * @return true if confirmed, false if confirmation is required */ public boolean confirm(CommandSender sender, String[] args, Message message) { String command = (("/" + getCommandStart()) + " ") + StringUtils.join(args, " ", 1, args.length); long now = System.currentTimeMillis(); CommandTime last = lastUsed.get(sender.getName()); if (((last != null) && last.command.equalsIgnoreCase(command)) && (last.time > (now - (1000 * 60)))) { return true; } message.prefix().append(Message.fromKey("confirm-yes").replacements(command)).send(sender); lastUsed.put(sender.getName(), new CommandTime(command, now)); return false; }
3.26
AreaShop_CommandAreaShop_getTabCompleteList_rdh
/** * Get a list of string to complete a command with (raw list, not matching ones not filtered out). * * @param toComplete * The number of the argument that has to be completed * @param start * The already given start of the command * @param sender * The CommandSender that wants to tab complete * @return A collection with all the possibilities for argument to complete */ public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) { return new ArrayList<>(); }
3.26
AreaShop_Utils_evaluateToDouble_rdh
/** * Evaluate string input to a number. * Uses JavaScript for expressions. * * @param input * The input string * @param region * The region to apply replacements for and use for logging * @return double evaluated from the input or a very high default in case of a script exception */ public static double evaluateToDouble(String input, GeneralRegion region) { // Replace variables input = Message.fromString(input).replacements(region).getSingle(); // Check for simple number if (isDouble(input)) { return Double.parseDouble(input); } // Lazy init scriptEngine if (scriptEngine == null) { scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript"); } // Evaluate expression Object result; try { result = scriptEngine.eval(input); } catch (ScriptException e) { AreaShop.warn("Price of region", region.getName(), ("is set with an invalid expression: '" + input) + "', exception:", ExceptionUtils.getStackTrace(e)); return 9.9999999999E10;// High fallback for safety } // Handle the result if (Utils.isDouble(result.toString())) {return Double.parseDouble(result.toString()); } else { AreaShop.warn("Price of region", region.getName(), ("is set with the expression '" + input) + "' that returns a result that is not a number:", result); return 9.9999999999E10;// High fallback for safety } }
3.26