name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
AreaShop_Utils_getDurationFromMinutesOrStringInput_rdh
/** * Parse a time setting that could be minutes or a duration string. * * @param input * The string to parse * @return milliseconds that the string indicates */ public static long getDurationFromMinutesOrStringInput(String input) { long number; try { number = Long.parseLong(input);if (number != (-1)) { number *= 60 * 1000; } return number; } catch (NumberFormatException e) { return durationStringToLong(input); } }
3.26
AreaShop_Utils_getImportantBuyRegions_rdh
/** * Get the most important buy AreaShop regions. * - Returns highest priority, child instead of parent regions. * * @param location * The location to check for regions * @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority */ public static List<BuyRegion> getImportantBuyRegions(Location location) { List<BuyRegion> result = new ArrayList<>(); for (GeneralRegion region : getImportantRegions(location, RegionType.BUY)) { result.add(((BuyRegion) (region)));} return result; }
3.26
AreaShop_Utils_toName_rdh
/** * Conversion to name by uuid object. * * @param uuid * The uuid in string format * @return the name of the player */ public static String toName(UUID uuid) { if (uuid == null) { return ""; } else { String name = Bukkit.getOfflinePlayer(uuid).getName(); if (name != null) { return name; } return ""; } }
3.26
AreaShop_Utils_configToLocation_rdh
/** * Create a location from a map, reconstruction from the config values. * * @param config * The config section to reconstruct from * @return The location */ public static Location configToLocation(ConfigurationSection config) { if ((((((config == null) || (!config.isString("world"))) || (!config.isDouble("x"))) || (!config.isDouble("y"))) || (!config.isDouble("z"))) || (Bukkit.getWorld(config.getString("world")) == null)) { return null; } Location result = new Location(Bukkit.getWorld(config.getString("world")), config.getDouble("x"), config.getDouble("y"), config.getDouble("z")); if (config.isString("yaw") && config.isString("pitch")) { result.setPitch(Float.parseFloat(config.getString("pitch"))); result.setYaw(Float.parseFloat(config.getString("yaw"))); } return result; }
3.26
AreaShop_Utils_getDurationFromSecondsOrStringInput_rdh
/** * Parse a time setting that could be seconds or a duration string. * * @param input * The string to parse * @return seconds that the string indicates */ public static long getDurationFromSecondsOrStringInput(String input) { long number; try { number = Long.parseLong(input); if (number != (-1)) { number *= 1000; } return number; } catch (NumberFormatException e) { return durationStringToLong(input); } }
3.26
AreaShop_Utils_applyColors_rdh
/** * Convert color and formatting codes to bukkit values. * * @param input * Start string with color and formatting codes in it * @return String with the color and formatting codes in the bukkit format */ public static String applyColors(String input) { String result = null; if (input != null) {result = ChatColor.translateAlternateColorCodes('&', input); } return result; }
3.26
AreaShop_Utils_initialize_rdh
/** * Initialize the utilities class with constants. * * @param pluginConfig * The config of the plugin */ public static void initialize(YamlConfiguration pluginConfig) { config = pluginConfig;// Setup individual identifiers seconds = getSetAndDefaults("seconds"); minutes = getSetAndDefaults("minutes"); hours = getSetAndDefaults("hours"); days = getSetAndDefaults("days"); weeks = getSetAndDefaults("weeks"); months = getSetAndDefaults("months"); years = getSetAndDefaults("years"); // Setup all time identifiers identifiers = new HashSet<>(); identifiers.addAll(seconds); identifiers.addAll(minutes); identifiers.addAll(hours); identifiers.addAll(days); identifiers.addAll(weeks); identifiers.addAll(months); identifiers.addAll(years); suffixes = new HashMap<>();// This stuff should not be necessary, but it is, getConfigurationSection() does not do proper fallback to defaults! // TODO: Create a custom configuration that fixes this behavior ConfigurationSection suffixesSection = null; if (config.isSet("metricSymbols")) { suffixesSection = config.getConfigurationSection("metricSymbols"); } else { Configuration defaults = config.getDefaults(); if (defaults != null) { suffixesSection = defaults.getConfigurationSection("metricSymbols"); } } if (suffixesSection != null) { for (String key : suffixesSection.getKeys(false)) { try { suffixes.put(Double.parseDouble(key), suffixesSection.getString(key)); } catch (NumberFormatException e) { Log.warn(("Key '" + key) + "' in the metricSymbols section of config.yml is not a number!"); } } } }
3.26
AreaShop_Utils_isNumeric_rdh
/** * Check if an input is numeric. * * @param input * The input to check * @return true if the input is numeric, otherwise false */ @SuppressWarnings("ResultOfMethodCallIgnored") public static boolean isNumeric(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException ignored) { return false; } }
3.26
AreaShop_Utils_millisToHumanFormat_rdh
/** * Convert milliseconds to a human readable format. * * @param milliseconds * The amount of milliseconds to convert * @return A formatted string based on the language file */ public static String millisToHumanFormat(long milliseconds) { long timeLeft = milliseconds + 500; // To seconds timeLeft /= 1000; if (timeLeft <= 0) {return Message.fromKey("timeleft-ended").getPlain(); } else if (timeLeft == 1) { return Message.fromKey("timeleft-second").replacements(timeLeft).getPlain(); } else if (timeLeft <= 120) { return Message.fromKey("timeleft-seconds").replacements(timeLeft).getPlain();} // To minutes timeLeft /= 60; if (timeLeft <= 120) { return Message.fromKey("timeleft-minutes").replacements(timeLeft).getPlain(); } // To hours timeLeft /= 60; if (timeLeft <= 48) { return Message.fromKey("timeleft-hours").replacements(timeLeft).getPlain(); } // To days timeLeft /= 24; if (timeLeft <= 60) { return Message.fromKey("timeleft-days").replacements(timeLeft).getPlain(); } // To months timeLeft /= 30; if (timeLeft <= 24) { return Message.fromKey("timeleft-months").replacements(timeLeft).getPlain(); } // To years timeLeft /= 12; return Message.fromKey("timeleft-years").replacements(timeLeft).getPlain(); }
3.26
AreaShop_Utils_checkTimeFormat_rdh
/** * Checks if the string is a correct time period. * * @param time * String that has to be checked * @return true if format is correct, false if not */ public static boolean checkTimeFormat(String time) { // Check if the string is not empty and check the length if ((((time == null) || (time.length() <= 1)) || (time.indexOf(' ') == (-1))) || (time.indexOf(' ') >= (time.length() - 1))) { return false; } // Check if the suffix is one of these values String suffix = time.substring(time.indexOf(' ') + 1); if (!identifiers.contains(suffix)) { return false; } // check if the part before the space is a number String prefix = time.substring(0, time.indexOf(' ')); return prefix.matches("\\d+"); }
3.26
AreaShop_Utils_durationStringToLong_rdh
/** * Methode to tranlate a duration string to a millisecond value. * * @param duration * The duration string * @return The duration in milliseconds translated from the durationstring, or if it is invalid then 0 */ public static long durationStringToLong(String duration) { if (duration == null) { return 0; } else if ((duration.equalsIgnoreCase("disabled") || duration.equalsIgnoreCase("unlimited")) || duration.isEmpty()) { return -1; } else if (duration.indexOf(' ') == (-1)) { return 0; } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(0); String durationString = duration.substring(duration.indexOf(' ') + 1); int durationInt = 0; try { durationInt = Integer.parseInt(duration.substring(0, duration.indexOf(' '))); } catch (NumberFormatException exception) { // No Number found, add zero } if (seconds.contains(durationString)) { calendar.add(Calendar.SECOND, durationInt); } else if (minutes.contains(durationString)) { calendar.add(Calendar.MINUTE, durationInt); } else if (hours.contains(durationString)) { calendar.add(Calendar.HOUR, durationInt); } else if (days.contains(durationString)) { calendar.add(Calendar.DAY_OF_MONTH, durationInt); } else if (weeks.contains(durationString)) { calendar.add(Calendar.DAY_OF_MONTH, durationInt * 7); } else if (months.contains(durationString)) { calendar.add(Calendar.MONTH, durationInt); } else if (years.contains(durationString)) { calendar.add(Calendar.YEAR, durationInt); } else { AreaShop.warn("Unknown duration indicator:", durationString, "check if config.yml has the correct time indicators"); } return calendar.getTimeInMillis(); }
3.26
AreaShop_Utils_getImportantWorldEditRegions_rdh
/** * Get a list of regions around a location. * - Returns highest priority, child instead of parent regions * * @param location * The location to check for regions * @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority */ public static List<ProtectedRegion> getImportantWorldEditRegions(Location location) { List<ProtectedRegion> result = new ArrayList<>(); Set<ProtectedRegion> regions = AreaShop.getInstance().getWorldGuardHandler().getApplicableRegionsSet(location); if (regions != null) { boolean first = true;for (ProtectedRegion pr : regions) { if (first) { result.add(pr); first = false; } else if (pr.getPriority() > result.get(0).getPriority()) {result.clear(); result.add(pr); } else if ((pr.getParent() != null) && pr.getParent().equals(result.get(0))) { result.clear(); result.add(pr); } else { result.add(pr); } } } return result; }
3.26
AreaShop_Utils_getRegionsInSelection_rdh
// ====================================================================== // Methods to get WorldGuard or AreaShop regions by location or selection // ====================================================================== /** * Get all AreaShop regions intersecting with a WorldEdit selection. * * @param selection * The selection to check * @return A list with all the AreaShop regions intersecting with the selection */ public static List<GeneralRegion> getRegionsInSelection(WorldEditSelection selection) { ArrayList<GeneralRegion> result = new ArrayList<>(); for (ProtectedRegion region : getWorldEditRegionsInSelection(selection)) { GeneralRegion asRegion = AreaShop.getInstance().getFileManager().getRegion(region.getId()); if (asRegion != null) { result.add(asRegion); } } return result; }
3.26
AreaShop_Utils_createCommaSeparatedList_rdh
/** * Create a comma-separated list. * * @param input * Collection of object which should be concatenated with comma's in between (skipping null values) * @return Innput object concatenated with comma's in between */ public static String createCommaSeparatedList(Collection<?> input) { StringBuilder result = new StringBuilder(); boolean first = true; for (Object object : input) { if (object != null) { if (first) { first = false; result.append(object.toString()); } else { result.append(", ").append(object.toString()); } } } return result.toString(); }
3.26
AreaShop_Utils_getOnlinePlayers_rdh
/** * Gets the online players. * Provides backwards compatibility for 1.7- where it returns an array * * @return Online players */ @SuppressWarnings("unchecked") public static Collection<? extends Player> getOnlinePlayers() { try { Method v8 = Server.class.getMethod("getOnlinePlayers"); if (v8.getReturnType().equals(Collection.class)) { return ((Collection<? extends Player>) (v8.invoke(Bukkit.getServer()))); } else { return Arrays.asList(((Player[]) (v8.invoke(Bukkit.getServer()))));} } catch (Exception ex) { AreaShop.debug("getOnlinePlayers error: " + ex.getMessage()); } return new HashSet<>(); }
3.26
AreaShop_Utils_getImportantRentRegions_rdh
/** * Get the most important rental AreaShop regions. * - Returns highest priority, child instead of parent regions. * * @param location * The location to check for regions * @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority */ public static List<RentRegion> getImportantRentRegions(Location location) { List<RentRegion> result = new ArrayList<>(); for (GeneralRegion region : getImportantRegions(location, RegionType.RENT)) { result.add(((RentRegion) (region)));} return result; }
3.26
AreaShop_Utils_toUniqueId_rdh
/** * Conversion from name to uuid. * * @param name * The name of the player * @return The uuid of the player */ // Fake deprecation by Bukkit to inform developers, method will stay @SuppressWarnings("deprecation") public static String toUniqueId(String name) { if (name == null) { return null; } else { return Bukkit.getOfflinePlayer(name).getUniqueId().toString(); } }
3.26
AreaShop_Utils_getSetAndDefaults_rdh
/** * Get a string list from the config, combined with the entries specified in the default config. * * @param path * The path to read the lists from * @return List with all values defined in the config and the default config combined */ private static Set<String> getSetAndDefaults(String path) { Set<String> result = new HashSet<>(config.getStringList(path)); ConfigurationSection defaults = config.getDefaults(); if (defaults != null) { result.addAll(defaults.getStringList(path)); } return result; }
3.26
AreaShop_Utils_getRegions_rdh
/** * Get all AreaShop regions containing a location. * * @param location * The location to check * @return A list with all the AreaShop regions that contain the location */ public static List<GeneralRegion> getRegions(Location location) { return getRegionsInSelection(new WorldEditSelection(location.getWorld(), location, location)); }
3.26
AreaShop_Utils_isDouble_rdh
/** * Check if a string is a double. * * @param input * The input * @return true if the input is a double, otherwise false */ @SuppressWarnings("ResultOfMethodCallIgnored") public static boolean isDouble(String input) { try { Double.parseDouble(input); return true; } catch (NumberFormatException e) { return false; } }
3.26
AreaShop_Utils_combinedMessage_rdh
/** * Create a message with a list of parts. * * @param replacements * The parts to use * @param messagePart * The message to use for the parts * @param combiner * The string to use as combiner * @return A Message object containing the parts combined into one message */ public static Message combinedMessage(Collection<?> replacements, String messagePart, String combiner) { Message result = Message.empty(); boolean first = true; for (Object part : replacements) { if (first) { first = false; } else { result.append(combiner);} result.append(Message.fromKey(messagePart).replacements(part)); } return result; }
3.26
AreaShop_Utils_getImportantRegions_rdh
/** * Get the most important AreaShop regions. * - Returns highest priority, child instead of parent regions. * * @param location * The location to check for regions * @param type * The type of regions to look for, null for all * @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority */ public static List<GeneralRegion> getImportantRegions(Location location, GeneralRegion.RegionType type) { List<GeneralRegion> result = new ArrayList<>(); Set<ProtectedRegion> v35 = AreaShop.getInstance().getWorldGuardHandler().getApplicableRegionsSet(location); if (v35 != null) { List<GeneralRegion> candidates = new ArrayList<>(); for (ProtectedRegion pr : v35) { GeneralRegion region = AreaShop.getInstance().getFileManager().getRegion(pr.getId()); if ((region != null) && ((((type == RegionType.RENT) && (region instanceof RentRegion)) || ((type == RegionType.BUY) && (region instanceof BuyRegion))) || (type == null))) { candidates.add(region); } } boolean first = true; for (GeneralRegion region : candidates) { if (region == null) { AreaShop.debug("skipped null region"); continue; } if (first) { result.add(region); first = false; } else if (region.getRegion().getPriority() > result.get(0).getRegion().getPriority()) { result.clear(); result.add(region); } else if ((region.getRegion().getParent() != null) && region.getRegion().getParent().equals(result.get(0).getRegion())) { result.clear(); result.add(region); } else { result.add(region); } } } return new ArrayList<>(result); }
3.26
AreaShop_Utils_locationToConfig_rdh
/** * Create a map from a location, to save it in the config. * * @param location * The location to transform * @param setPitchYaw * true to save the pitch and yaw, otherwise false * @return The map with the location values */ public static ConfigurationSection locationToConfig(Location location, boolean setPitchYaw) { if (location == null) { return null; } ConfigurationSection v9 = new YamlConfiguration(); v9.set("world", location.getWorld().getName()); v9.set("x", location.getX()); v9.set("y", location.getY()); v9.set("z", location.getZ()); if (setPitchYaw) { v9.set("yaw", Float.toString(location.getYaw())); v9.set("pitch", Float.toString(location.getPitch())); } return v9; }
3.26
AreaShop_Utils_millisToTicks_rdh
/** * Convert milliseconds to ticks. * * @param milliseconds * Milliseconds to convert * @return milliseconds divided by 50 (20 ticks per second) */ public static long millisToTicks(long milliseconds) { return milliseconds / 50; }
3.26
AreaShop_Utils_formatCurrency_rdh
/** * Format the currency amount with the characters before and after. * * @param amount * Amount of money to format * @return Currency character format string */ public static String formatCurrency(double amount) { String before = config.getString("moneyCharacter"); before = before.replace(AreaShop.currencyEuro, "€"); String after = config.getString("moneyCharacterAfter");after = after.replace(AreaShop.currencyEuro, "€"); String result; // Check for infinite and NaN if (Double.isInfinite(amount)) {result = "∞";// Infinite symbol } else if (Double.isNaN(amount)) { result = "NaN"; } else { BigDecimal bigDecimal = BigDecimal.valueOf(amount); boolean stripTrailingZeros = false; int fractionalNumber = config.getInt("fractionalNumbers"); // Add metric suffix if necessary if (config.getDouble("metricSuffixesAbove") != (-1)) { String suffix = null; double divider = 1; for (Double number : suffixes.keySet()) { if ((amount >= number) && (number > divider)) { divider = number; suffix = suffixes.get(number); } } if (suffix != null) { bigDecimal = BigDecimal.valueOf(amount / divider); after = suffix + after; fractionalNumber = config.getInt("fractionalNumbersShort"); stripTrailingZeros = true; } } // Round if necessary if (fractionalNumber >= 0) { bigDecimal = bigDecimal.setScale(fractionalNumber, RoundingMode.HALF_UP); } result = bigDecimal.toString(); if (config.getBoolean("hideEmptyFractionalPart")) { // Strip zero fractional: 12.00 -> 12 if ((bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) && result.contains(".")) { result = result.substring(0, result.indexOf('.')); } // Strip zeros from suffixed numbers: 1.20M -> 1.2M if (stripTrailingZeros && result.contains(".")) { result = result.replaceAll("0+$", ""); } } } result = result.replace(".", config.getString("decimalMark")); Message resultMessage = Message.fromString(result); resultMessage.prepend(before); resultMessage.append(after); return resultMessage.getSingle(); }
3.26
AreaShop_Utils_yawToFacing_rdh
/** * Get the facing direction based on the yaw. * * @param yaw * The horizontal angle that for example the player is looking * @return The Block Face of the angle */public static BlockFace yawToFacing(float yaw) { return facings[Math.round(yaw / 45.0F) & 0x7]; }
3.26
AreaShop_Utils_getDurationFromMinutesOrString_rdh
/** * Get setting from config that could be only a number indicating minutes. * or a string indicating a duration string. * * @param path * Path of the setting to read * @return milliseconds that the setting indicates */ public static long getDurationFromMinutesOrString(String path) { if (config.isLong(path) || config.isInt(path)) { long setting = config.getLong(path); if (setting != (-1)) { setting *= 60 * 1000; } return setting; } else { return durationStringToLong(config.getString(path));} }
3.26
AreaShop_TeleportFeature_m1_rdh
/** * Get the start location of a safe teleport search. * * @param player * The player to get it for * @param toSign * true to try teleporting to the first sign, false for teleporting to the region * @return The start location */ private Location m1(Player player, Value<Boolean> toSign) { Location startLocation = null; ProtectedRegion worldguardRegion = getRegion().getRegion(); // Try to get sign location List<RegionSign> signs = getRegion().getSignsFeature().getSigns(); boolean signAvailable = !signs.isEmpty(); if (toSign.get()) { if (signAvailable) { // Use the location 1 below the sign to prevent weird spawing above the sign startLocation = signs.get(0).getLocation();// .subtract(0.0, 1.0, 0.0); startLocation.setPitch(player.getLocation().getPitch()); startLocation.setYaw(player.getLocation().getYaw()); // Move player x blocks away from the sign double v57 = getRegion().getDoubleSetting("general.teleportSignDistance"); if (v57 > 0) {BlockFace facing = getRegion().getSignsFeature().getSigns().get(0).getFacing(); Vector facingVector = new Vector(facing.getModX(), facing.getModY(), facing.getModZ()).normalize().multiply(v57); startLocation.setX(startLocation.getBlockX() + 0.5); startLocation.setZ(startLocation.getBlockZ() + 0.5); startLocation.add(facingVector); } } else { // No sign available getRegion().message(player, "teleport-changedToNoSign"); toSign.set(false); } } // Use teleportation location that is set for the region if ((startLocation == null) && hasTeleportLocation()) { startLocation = getTeleportLocation(); } // Calculate a default location if (startLocation == null) { // Set to block in the middle, y configured in the config Vector regionMin = AreaShop.getInstance().getWorldGuardHandler().getMinimumPoint(worldguardRegion); Vector regionMax = AreaShop.getInstance().getWorldGuardHandler().getMaximumPoint(worldguardRegion); Vector middle = regionMin.clone().midpoint(regionMax); String configSetting = getRegion().getStringSetting("general.teleportLocationY"); if ("bottom".equalsIgnoreCase(configSetting)) { middle = middle.setY(regionMin.getBlockY()); } else if ("top".equalsIgnoreCase(configSetting)) { middle = middle.setY(regionMax.getBlockY()); } else if ("middle".equalsIgnoreCase(configSetting)) { middle = middle.setY(middle.getBlockY()); } else { try { int vertical = Integer.parseInt(configSetting); middle = middle.setY(vertical); } catch (NumberFormatException e) { AreaShop.warn(("Could not parse general.teleportLocationY: '" + configSetting) + "'"); } } startLocation = new Location(getRegion().getWorld(), middle.getX(), middle.getY(), middle.getZ(), player.getLocation().getYaw(), player.getLocation().getPitch()); } // Set location in the center of the block startLocation.setX(startLocation.getBlockX() + 0.5);startLocation.setZ(startLocation.getBlockZ() + 0.5); return startLocation; }
3.26
AreaShop_TeleportFeature_cannotSpawnOn_rdh
/** * Check if a player can spawn on here. * * @param material * Material to check (assumed that this is below the feet) * @return true when it is safe to spawn on top of, otherwise false */ private static boolean cannotSpawnOn(Material material) { String name = material.name(); return (((((((((name.equals("CACTUS") || name.contains("PISTON")) || name.contains("SIGN")) || name.contains("DOOR")) || name.contains("PLATE")) || name.contains("REDSTONE_LAMP")) || name.contains("FENCE")) || name.contains("GLASS_PANE")) || name.contains("THIN_GLASS")) || name.equals("DRAGON_EGG")) || name.contains("MAGMA"); }
3.26
AreaShop_TeleportFeature_isSafe_rdh
/** * Checks if a certain location is safe to teleport to. * * @param location * The location to check * @return true if it is safe, otherwise false */ private boolean isSafe(Location location) { Block feet = location.getBlock(); Block head = feet.getRelative(BlockFace.UP); Block below = feet.getRelative(BlockFace.DOWN); Block above = head.getRelative(BlockFace.UP); // Check the block at the feet and head of the player if ((feet.getType().isSolid() && (!canSpawnIn(feet.getType()))) || feet.isLiquid()) { return false; } else if ((head.getType().isSolid() && (!canSpawnIn(head.getType()))) || head.isLiquid()) { return false; } else if (((!below.getType().isSolid()) || cannotSpawnOn(below.getType())) || below.isLiquid()) { return false; } else if (above.isLiquid() || cannotSpawnBeside(above.getType())) { return false; } // Get all blocks around the player (below foot level, foot level, head level and above head level) Set<Material> around = new HashSet<>(); for (int y = 0; y <= 3; y++) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { // Skip blocks in the column of the player if ((x == 0) && (z == 0)) { continue; } around.add(below.getRelative(x, y, z).getType()); } } } // Check the blocks around the player for (Material material : around) { if (cannotSpawnBeside(material)) { return false; } } return true; }
3.26
AreaShop_TeleportFeature_teleportPlayer_rdh
/** * Teleport a player to the region when he has permissions for it. * * @param player * Player that should be teleported * @return true if the teleport succeeded, otherwise false */ public boolean teleportPlayer(Player player) { return teleportPlayer(player, false, true); }
3.26
AreaShop_TeleportFeature_canSpawnIn_rdh
/** * Check if a player can spawn in here. * * @param material * Material to check (assumed that this is at the feet or head level) * @return true when it is safe to spawn inside, otherwise false */ private static boolean canSpawnIn(Material material) { String name = material.name(); return ((name.contains("DOOR") || name.contains("SIGN")) || name.contains("PLATE"))// Redstone plates || name.equals("DRAGON_EGG");}
3.26
AreaShop_TeleportFeature_cannotSpawnBeside_rdh
/** * Check if a player can spawn next to it. * * @param material * Material to check (assumed that this is somewhere around the player) * @return true when it is safe to spawn next to, otherwise false */ private static boolean cannotSpawnBeside(Material material) { String name = material.name(); return ((name.contains("LAVA") || name.contains("CACTUS")) || name.equals("FIRE")) || name.contains("MAGMA"); }
3.26
AreaShop_TeleportFeature_getTeleportLocation_rdh
/** * Get the teleportlocation set for this region. * * @return The teleport location, or null if not set */ public Location getTeleportLocation() { return Utils.configToLocation(getRegion().getConfigurationSectionSetting("general.teleportLocation")); }
3.26
AreaShop_Materials_signNameToMaterial_rdh
/** * Get material based on a sign material name. * * @param name * Name of the sign material * @return null if not a sign, otherwise the material matching the name (when the material is not available on the current minecraft version, it returns the base type) */ public static Material signNameToMaterial(String name) { // Expected null case if (!isSign(name)) { return null; } Material result = null; if (legacyMaterials) { // 1.12 and lower just know SIGN_POST, WALL_SIGN and SIGN if (FLOOR_SIGN_TYPES.contains(name)) { result = Material.getMaterial("SIGN_POST"); } else if (WALL_SIGN_TYPES.contains(name)) { result = Material.getMaterial("WALL_SIGN"); if (result == null) { result = Material.getMaterial("SIGN"); } } } else { // Try saved name (works for wood types on 1.14, regular types for below) result = Material.getMaterial(name); if (result == null) { // Cases for 1.13, which don't know wood types, but need new materials if (FLOOR_SIGN_TYPES.contains(name)) {// SIGN -> OAK_SIGN for 1.14 result = Material.getMaterial("OAK_SIGN"); // Fallback for 1.13 if (result == null) { result = Material.getMaterial("SIGN"); } } else if (WALL_SIGN_TYPES.contains(name)) { // WALL_SIGN -> OAK_WALL_SIGN for 1.14 result = Material.getMaterial("OAK_WALL_SIGN"); // Fallback for 1.13 if (result == null) { result = Material.getMaterial("WALL_SIGN"); } } } } if (result == null) { AreaShop.debug("Materials.get() null result:", name, "legacyMaterials:", legacyMaterials); } return result; }
3.26
AreaShop_Materials_isSign_rdh
/** * Check if a Material is a sign (of either the wall or floor type). * * @param name * String to check * @return true if the given material is a sign */ public static boolean isSign(String name) { return (name != null) && (FLOOR_SIGN_TYPES.contains(name) || WALL_SIGN_TYPES.contains(name)); }
3.26
AreaShop_RegionAccessSet_asUniqueIdList_rdh
/** * Get this access set as a list of player UUIDs. * * @return List of player UUIDs, first players already added by UUID, then players added by name, groups are not in the list */ public List<UUID> asUniqueIdList() { List<UUID> result = new ArrayList<>(); result.addAll(playerUniqueIds); for (String playerName : playerNames) { OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerName); if ((offlinePlayer != null) && (offlinePlayer.getUniqueId() != null)) { result.add(offlinePlayer.getUniqueId()); }} return result; }
3.26
AreaShop_RegionAccessSet_getPlayerUniqueIds_rdh
/** * Get the players that have been added by uuid. * * @return Set with players that have been added by uuid */ public Set<UUID> getPlayerUniqueIds() { return playerUniqueIds; }
3.26
AreaShop_RegionAccessSet_getGroupNames_rdh
/** * Get the groups. * * @return Set with groups added to this RegionAccessSet. */ public Set<String> getGroupNames() { return groupNames; }
3.26
AreaShop_RegionAccessSet_getPlayerNames_rdh
/** * Get the players that have been added by name. * * @return Set with players that have been added by name */ public Set<String> getPlayerNames() { return playerNames; }
3.26
AreaShop_AreaShop_getSignlinkerManager_rdh
/** * Get the SignLinkerManager. * Handles sign linking mode. * * @return The SignLinkerManager */ public SignLinkerManager getSignlinkerManager() { return signLinkerManager; }
3.26
AreaShop_AreaShop_getBukkitHandler_rdh
/** * Get the BukkitHandler, for sign interactions. * * @return BukkitHandler */ public BukkitInterface getBukkitHandler() { return this.bukkitInterface; }
3.26
AreaShop_AreaShop_registerDynamicPermissions_rdh
/** * Register dynamic permissions controlled by config settings. */ private void registerDynamicPermissions() { // Register limit groups of amount of regions a player can have ConfigurationSection v33 = getConfig().getConfigurationSection("limitGroups"); if (v33 == null) { return;} for (String group : v33.getKeys(false)) { if (!"default".equals(group)) { Permission perm = new Permission("areashop.limits." + group); try { Bukkit.getPluginManager().addPermission(perm); } catch (IllegalArgumentException e) { warn("Could not add the following permission to be used as limit: " + perm.getName()); } } } Bukkit.getPluginManager().recalculatePermissionDefaults(Bukkit.getPluginManager().getPermission("playerwarps.limits")); }
3.26
AreaShop_AreaShop_onEnable_rdh
/** * Called on start or reload of the server. */ @Override public void onEnable() { AreaShop.instance = this; Do.init(this); managers = new HashSet<>(); boolean error = false; // Find WorldEdit integration version to load String weVersion = null; String rawWeVersion = null; String weBeta = null; Plugin plugin = getServer().getPluginManager().getPlugin("WorldEdit"); if ((!(plugin instanceof WorldEditPlugin)) || (!plugin.isEnabled())) { m0("WorldEdit plugin is not present or has not loaded correctly"); error = true; } else { worldEdit = ((WorldEditPlugin) (plugin)); rawWeVersion = worldEdit.getDescription().getVersion(); // Find beta version Pattern pattern = Pattern.compile("beta-?\\d+"); Matcher matcher = pattern.matcher(rawWeVersion); if (matcher.find()) { weBeta = matcher.group(); } // Get correct WorldEditInterface (handles things that changed version to version) if (worldEdit.getDescription().getVersion().startsWith("5.")) { weVersion = "5"; } else if (worldEdit.getDescription().getVersion().startsWith("6.")) { weVersion = "6"; } else if ("beta-01".equalsIgnoreCase(weBeta)) { weVersion = "7_beta_1"; } else { // beta-02 and beta-03 also have the new vector system already weVersion = "7_beta_4"; } weVersion = "WorldEditHandler" + weVersion; } // Find WorldGuard integration version to load String wgVersion = null; String rawWgVersion = null; int major = 0; int minor = 0; int fixes = 0; Integer build = null; plugin = getServer().getPluginManager().getPlugin("WorldGuard"); if ((!(plugin instanceof WorldGuardPlugin)) || (!plugin.isEnabled())) { m0("WorldGuard plugin is not present or has not loaded correctly"); error = true; } else {worldGuard = ((WorldGuardPlugin) (plugin)); // Get correct WorldGuardInterface (handles things that changed version to version) try { rawWgVersion = worldGuard.getDescription().getVersion();if (rawWgVersion.contains("-SNAPSHOT;")) { String buildNumber = rawWgVersion.substring(rawWgVersion.indexOf("-SNAPSHOT;") + 10); if (buildNumber.contains("-")) { buildNumber = buildNumber.substring(0, buildNumber.indexOf('-')); if (Utils.isNumeric(buildNumber)) { build = Integer.parseInt(buildNumber); } else { warn((("Could not correctly parse the build of WorldGuard, raw version: " + rawWgVersion) + ", buildNumber: ") + buildNumber); } } } // Clear stuff from the version string that is not a number String[] versionParts = rawWgVersion.split("\\."); for (int i = 0; i < versionParts.length; i++) { Pattern pattern = Pattern.compile("^\\d+"); Matcher matcher = pattern.matcher(versionParts[i]); if (matcher.find()) { versionParts[i] = matcher.group(); } } // Find major, minor and fix numbers try { if (versionParts.length > 0) { major = Integer.parseInt(versionParts[0]); } if (versionParts.length > 1) { minor = Integer.parseInt(versionParts[1]); } if (versionParts.length > 2) { fixes = Integer.parseInt(versionParts[2]); } } catch (NumberFormatException e) { warn("Something went wrong while parsing WorldGuard version number: " + rawWgVersion); } // Determine correct implementation to use if (rawWgVersion.startsWith("5.")) { wgVersion = "5"; } else if (((major == 6) && (minor == 1)) && (fixes < 3)) { wgVersion = "6"; } else if (major == 6) { if ((build != null) && (build == 1672)) { error = true; m0("Build 1672 of WorldGuard is broken, update to a later build or a stable version!"); } else if ((build != null) && (build < 1672)) { wgVersion = "6"; } else { wgVersion = "6_1_3"; } } else if ("beta-01".equalsIgnoreCase(weBeta)) { // When using WorldEdit beta-01, we need to use the WorldGuard variant with the old vector system wgVersion = "7_beta_1"; } else { // Even though the WorldGuard file is called beta-02, the reported version is still beta-01! wgVersion = "7_beta_2"; } } catch (Exception e) { // If version detection fails, at least try to load the latest version warn("Parsing the WorldGuard version failed, assuming version 7_beta_2:", rawWgVersion); wgVersion = "7_beta_2"; } wgVersion = "WorldGuardHandler" + wgVersion; } // Check if FastAsyncWorldEdit is installed boolean fawe; try { Class.forName("com.boydti.fawe.Fawe"); fawe = true; } catch (ClassNotFoundException ignore) { fawe = false; } if (fawe) { boolean useNewIntegration = true; List<String> standardIntegrationVersions = Arrays.asList("1.7", "1.8", "1.9", "1.10", "1.11", "1.12"); for (String standardIntegrationVersion : standardIntegrationVersions) {String version = Bukkit.getBukkitVersion(); // Detects '1.8', '1.8.3', '1.8-pre1' style versions if ((version.equals(standardIntegrationVersion) || version.startsWith(standardIntegrationVersion + ".")) || version.startsWith(standardIntegrationVersion + "-")) { useNewIntegration = false;break; } } if (useNewIntegration) { weVersion = "FastAsyncWorldEditHandler"; wgVersion = "FastAsyncWorldEditWorldGuardHandler"; } } // Load WorldEdit try { Class<?> v23 = Class.forName("me.wiefferink.areashop.handlers." + weVersion); // Check if we have a NMSHandler class at that location. if (WorldEditInterface.class.isAssignableFrom(v23)) { // Make sure it actually implements WorldEditInterface worldEditInterface = ((WorldEditInterface) (v23.getConstructor(AreaShopInterface.class).newInstance(this)));// Set our handler } } catch (Exception e) { m0((("Could not load the handler for WorldEdit (tried to load " + weVersion) + "), report this problem to the author: ") + ExceptionUtils.getStackTrace(e)); error = true; weVersion = null; } // Load WorldGuard try { Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers." + wgVersion); // Check if we have a NMSHandler class at that location. if (WorldGuardInterface.class.isAssignableFrom(clazz)) { // Make sure it actually implements WorldGuardInterface worldGuardInterface = ((WorldGuardInterface) (clazz.getConstructor(AreaShopInterface.class).newInstance(this)));// Set our handler } } catch (Exception e) { m0((("Could not load the handler for WorldGuard (tried to load " + wgVersion) + "), report this problem to the author:") + ExceptionUtils.getStackTrace(e)); error = true; wgVersion = null; } // Load Bukkit implementation String bukkitHandler; try { Class.forName("org.bukkit.block.data.type.WallSign"); bukkitHandler = "1_13"; } catch (ClassNotFoundException e) { bukkitHandler = "1_12"; } try { Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.BukkitHandler" + bukkitHandler); bukkitInterface = ((BukkitInterface) (clazz.getConstructor(AreaShopInterface.class).newInstance(this))); } catch (Exception e) { m0("Could not load the Bukkit handler (used for sign updates), tried to load:", bukkitHandler + ", report this problem to the author:", ExceptionUtils.getStackTrace(e)); error = true; bukkitHandler = null; } // Check if Vault is present if (getServer().getPluginManager().getPlugin("Vault") == null) { m0("Vault plugin is not present or has not loaded correctly"); error = true; }// Load all data from files and check versions fileManager = new FileManager();managers.add(fileManager); boolean loadFilesResult = fileManager.loadFiles(false); error = error || (!loadFilesResult); // Print loaded version of WG and WE in debug if (wgVersion != null) { AreaShop.debug("Loaded ", wgVersion, ((((((((((("(raw version:" + rawWgVersion) + ", major:") + major) + ", minor:") + minor) + ", fixes:") + fixes) + ", build:") + build) + ", fawe:") + fawe) + ")"); } if (weVersion != null) { AreaShop.debug("Loaded ", weVersion, ((("(raw version:" + rawWeVersion) + ", beta:") + weBeta) + ")"); } if (bukkitHandler != null) { AreaShop.debug("Loaded BukkitHandler", bukkitHandler); } setupLanguageManager(); if (error) { m0("The plugin has not started, fix the errors listed above"); } else { featureManager = new FeatureManager(); managers.add(featureManager); // Register the event listeners getServer().getPluginManager().registerEvents(new PlayerLoginLogoutListener(this), this); setupTasks(); // Startup the CommandManager (registers itself for the command) commandManager = new CommandManager(); managers.add(commandManager); // Create a signLinkerManager signLinkerManager = new SignLinkerManager(); managers.add(signLinkerManager); // Enable Metrics if config allows it if (getConfig().getBoolean("sendStats")) { Analytics.start(); }// Register dynamic permission (things declared in config) registerDynamicPermissions(); // Don't initialize the updatechecker if disabled in the config if (getConfig().getBoolean("checkForUpdates")) { githubUpdateCheck = new GithubUpdateCheck(AreaShop.getInstance(), "NLThijs48", "AreaShop").withVersionComparator((latestVersion, currentVersion) -> !cleanVersion(latestVersion).equals(cleanVersion(currentVersion))).checkUpdate(result -> { AreaShop.debug("Update check result:", result); if (!result.hasUpdate()) { return; } AreaShop.info(((("Update from AreaShop V" + cleanVersion(result.getCurrentVersion())) + " to AreaShop V") + cleanVersion(result.getLatestVersion())) + " available, get the latest version at https://www.spigotmc.org/resources/areashop.2991/"); for (Player player : Utils.getOnlinePlayers()) { notifyUpdate(player); } }); } } }
3.26
AreaShop_AreaShop_info_rdh
/** * Print an information message to the console. * * @param message * The message to print */ public static void info(Object... message) { AreaShop.getInstance().getLogger().info(StringUtils.join(message, " ")); }
3.26
AreaShop_AreaShop_setReady_rdh
/** * Set if the plugin is ready to be used or not (not to be used from another plugin!). * * @param ready * Indicate if the plugin is ready to be used */ public void setReady(boolean ready) { this.ready = ready; }
3.26
AreaShop_AreaShop_setChatprefix_rdh
/** * Set the chatprefix to use in the chat (loaded from config normally). * * @param chatprefix * The string to use in front of chat messages (supports formatting codes) */ public void setChatprefix(List<String> chatprefix) { this.chatprefix = chatprefix; }
3.26
AreaShop_AreaShop_debug_rdh
/** * Sends an debug message to the console. * * @param message * The message that should be printed to the console */ public static void debug(Object... message) { if (AreaShop.getInstance().debug) { info("Debug: " + StringUtils.join(message, " ")); } }
3.26
AreaShop_AreaShop_getWorldEditHandler_rdh
/** * Function to get WorldGuardInterface for version dependent things. * * @return WorldGuardInterface */ public WorldEditInterface getWorldEditHandler() { return this.worldEditInterface; }
3.26
AreaShop_AreaShop_getEconomy_rdh
/** * Function to get the Vault plugin. * * @return Economy */ public Economy getEconomy() { RegisteredServiceProvider<Economy> economy = getServer().getServicesManager().getRegistration(Economy.class); if ((economy == null) || (economy.getProvider() == null)) { m0("There is no economy provider to support Vault, make sure you installed an economy plugin");return null; } return economy.getProvider(); }
3.26
AreaShop_AreaShop_getCommandManager_rdh
/** * Function to get the CommandManager. * * @return the CommandManager */ public CommandManager getCommandManager() { return commandManager; }
3.26
AreaShop_AreaShop_getWorldGuardHandler_rdh
/** * Function to get WorldGuardInterface for version dependent things. * * @return WorldGuardInterface */ public WorldGuardInterface getWorldGuardHandler() { return this.worldGuardInterface; }
3.26
AreaShop_AreaShop_notifyUpdate_rdh
/** * Notify a player about an update if he wants notifications about it and an update is available. * * @param sender * CommandSender to notify */ public void notifyUpdate(CommandSender sender) { if (((githubUpdateCheck != null) && githubUpdateCheck.hasUpdate()) && sender.hasPermission("areashop.notifyupdate")) {AreaShop.getInstance().message(sender, "update-playerNotify", cleanVersion(githubUpdateCheck.getCurrentVersion()), cleanVersion(githubUpdateCheck.getLatestVersion())); } }
3.26
AreaShop_AreaShop_hasPermission_rdh
/** * Check for a permission of a (possibly offline) player. * * @param offlinePlayer * OfflinePlayer to check * @param permission * Permission to check * @return true if the player has the permission, false if the player does not have permission or, is offline and there is not Vault-compatible permission plugin */ public boolean hasPermission(OfflinePlayer offlinePlayer, String permission) { // Online, return through Bukkit if (offlinePlayer.getPlayer() != null) { return offlinePlayer.getPlayer().hasPermission(permission); } // Resolve while offline if possible Permission permissionProvider = getPermissionProvider(); if (permissionProvider != null) { // TODO: Should we provide a world here? return permissionProvider.playerHas(null, offlinePlayer, permission); } // Player offline and no offline permission provider available, safely say that there is no permission return false; }
3.26
AreaShop_AreaShop_getFeatureManager_rdh
/** * Get the FeatureManager. * Manages region specific features. * * @return The FeatureManager */ public FeatureManager getFeatureManager() { return featureManager; }
3.26
AreaShop_AreaShop_getWorldEdit_rdh
/** * Function to get the WorldEdit plugin. * * @return WorldEditPlugin */ @Override public WorldEditPlugin getWorldEdit() { return worldEdit; }
3.26
AreaShop_AreaShop_reload_rdh
/** * Reload all files of the plugin and update all regions. */ public void reload() { reload(null);}
3.26
AreaShop_AreaShop_m0_rdh
/** * Print an error to the console. * * @param message * The message to print */ public static void m0(Object... message) { AreaShop.getInstance().getLogger().severe(StringUtils.join(message, " ")); }
3.26
AreaShop_AreaShop_getConfig_rdh
/** * Return the config. */ @Override public YamlConfiguration getConfig() { return fileManager.getConfig(); }
3.26
AreaShop_AreaShop_getWorldGuard_rdh
/** * Function to get the WorldGuard plugin. * * @return WorldGuardPlugin */ @Override public WorldGuardPlugin getWorldGuard() { return worldGuard; }
3.26
AreaShop_AreaShop_warn_rdh
/** * Print a warning to the console. * * @param message * The message to print */ public static void warn(Object... message) { AreaShop.getInstance().getLogger().warning(StringUtils.join(message, " ")); }
3.26
AreaShop_AreaShop_debugTask_rdh
/** * Print debug message for periodic task. * * @param message * The message to print */ public static void debugTask(Object... message) { if (AreaShop.getInstance().getConfig().getBoolean("debugTask")) { AreaShop.debug(StringUtils.join(message, " ")); } }
3.26
AreaShop_AreaShop_getPermissionProvider_rdh
/** * Get the Vault permissions provider. * * @return Vault permissions provider */ public Permission getPermissionProvider() { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);if ((permissionProvider == null) || (permissionProvider.getProvider() == null)) { return null; } return permissionProvider.getProvider(); }
3.26
AreaShop_AreaShop_cleanVersion_rdh
/** * Cleanup a version number. * * @param version * Version to clean * @return Cleaned up version (removed prefixes and suffixes) */ private String cleanVersion(String version) { version = version.toLowerCase();// Strip 'v' as used on Github tags if (version.startsWith("v")) { version = version.substring(1); } // Strip build number as used by Jenkins if (version.contains("#")) { version = version.substring(0, version.indexOf("#")); } return version; }
3.26
AreaShop_AreaShop_setupLanguageManager_rdh
/** * Setup a new LanguageManager. */ private void setupLanguageManager() { languageManager = new LanguageManager(this, f0, getConfig().getString("language"), "EN", chatprefix); }
3.26
AreaShop_AreaShop_getRegionManager_rdh
/** * Get the RegionManager. * * @param world * World to get the RegionManager for * @return RegionManager for the given world, if there is one, otherwise null */ public RegionManager getRegionManager(World world) { return this.worldGuardInterface.getRegionManager(world); }
3.26
AreaShop_AreaShop_getFileManager_rdh
/** * Method to get the FileManager (loads/save regions and can be used to get regions). * * @return The fileManager */ public FileManager getFileManager() { return fileManager; }
3.26
AreaShop_AreaShop_getLanguageManager_rdh
/** * Function to get the LanguageManager. * * @return the LanguageManager */ public LanguageManager getLanguageManager() { return languageManager;}
3.26
AreaShop_AreaShop_isReady_rdh
/** * Indicates if the plugin is ready to be used. * * @return true if the plugin is ready, false otherwise */ public boolean isReady() { return ready; }
3.26
AreaShop_AreaShop_message_rdh
/** * Send a message to a target, prefixed by the default chat prefix. * * @param target * The target to send the message to * @param key * The key of the language string * @param replacements * The replacements to insert in the message */ public void message(Object target, String key, Object... replacements) { Message.fromKey(key).prefix().replacements(replacements).send(target); }
3.26
AreaShop_AreaShop_setupTasks_rdh
/** * Register all required tasks. */ private void setupTasks() { // Rent expiration timer long expirationCheck = Utils.millisToTicks(Utils.getDurationFromSecondsOrString("expiration.delay")); final AreaShop finalPlugin = this; if (expirationCheck > 0) { Do.syncTimer(expirationCheck, () -> { if (isReady()) { finalPlugin.getFileManager().checkRents(); AreaShop.debugTask("Checking rent expirations..."); } else { AreaShop.debugTask("Skipped checking rent expirations, plugin not ready"); }}); } // Inactive unrenting/selling timer long inactiveCheck = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("inactive.delay")); if (inactiveCheck > 0) { Do.syncTimer(inactiveCheck, () -> {if (isReady()) { finalPlugin.getFileManager().checkForInactiveRegions(); AreaShop.debugTask("Checking for regions with players that are inactive too long..."); } else { AreaShop.debugTask("Skipped checking for regions of inactive players, plugin not ready"); } }); } // Periodic updating of signs for timeleft tags long periodicUpdate = Utils.millisToTicks(Utils.getDurationFromSecondsOrString("signs.delay")); if (periodicUpdate > 0) { Do.syncTimer(periodicUpdate, () -> { if (isReady()) { finalPlugin.getFileManager().performPeriodicSignUpdate(); AreaShop.debugTask("Performing periodic sign update..."); } else { AreaShop.debugTask("Skipped performing periodic sign update, plugin not ready"); } }); } // Saving regions and group settings long saveFiles = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("saving.delay"));if (saveFiles > 0) { Do.syncTimer(saveFiles, () -> { if (isReady()) { finalPlugin.getFileManager().saveRequiredFiles(); AreaShop.debugTask("Saving required files..."); } else { AreaShop.debugTask("Skipped saving required files, plugin not ready"); } }); } // Sending warnings about rent regions to online players long expireWarning = Utils.millisToTicks(Utils.getDurationFromMinutesOrString("expireWarning.delay")); if (expireWarning > 0) { Do.syncTimer(expireWarning, () -> { if (isReady()) { finalPlugin.getFileManager().sendRentExpireWarnings(); AreaShop.debugTask("Sending rent expire warnings..."); } else { AreaShop.debugTask("Skipped sending rent expire warnings, plugin not ready"); } }); } // Update all regions on startup if (getConfig().getBoolean("updateRegionsOnStartup")) {Do.syncLater(20, () -> { finalPlugin.getFileManager().updateAllRegions(); AreaShop.debugTask("Updating all regions at startup..."); }); } }
3.26
AreaShop_AreaShop_onDisable_rdh
/** * Called on shutdown or reload of the server. */ @Override public void onDisable() { Bukkit.getServer().getScheduler().cancelTasks(this); // Cleanup managers for (Manager manager : managers) { manager.shutdown(); } managers = null; fileManager = null; languageManager = null; commandManager = null; signLinkerManager = null; featureManager = null; // Cleanup plugins worldGuard = null;worldGuardInterface = null; worldEdit = null; worldEditInterface = null; // Cleanup other stuff chatprefix = null; debug = false; ready = false; HandlerList.unregisterAll(this); }
3.26
AreaShop_AreaShop_debugI_rdh
/** * 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, " ")); }
3.26
AreaShop_AreaShop_setDebug_rdh
/** * Set if the plugin should output debug messages (loaded from config normally). * * @param debug * Indicates if the plugin should output debug messages or not */ public void setDebug(boolean debug) {this.debug = debug; }
3.26
AreaShop_AreaShop_messageNoPrefix_rdh
/** * Send a message to a target without a prefix. * * @param target * The target to send the message to * @param key * The key of the language string * @param replacements * The replacements to insert in the message */ public void messageNoPrefix(Object target, String key, Object... replacements) { Message.fromKey(key).replacements(replacements).send(target); }
3.26
AreaShop_InfoCommand_showSortedPagedList_rdh
/** * Display a page of a list of regions. * * @param sender * The CommandSender to send the messages to * @param regions * The regions to display * @param filterGroup * The group to filter the regions by * @param keyHeader * The header to print above the page * @param pageInput * The page number, if any * @param baseCommand * The command to execute for next/previous page (/areashop will be added) */ private void showSortedPagedList(CommandSender sender, List<? extends GeneralRegion> regions, RegionGroup filterGroup, String keyHeader, String pageInput, String baseCommand) { int maximumItems = 20; int itemsPerPage = maximumItems - 2; int page = 1; if ((pageInput != null) && Utils.isNumeric(pageInput)) { try { page = Integer.parseInt(pageInput); } catch (NumberFormatException e) { plugin.message(sender, "info-wrongPage", pageInput); return; } } if (filterGroup != null) { regions.removeIf(generalRegion -> !filterGroup.isMember(generalRegion)); } if (regions.isEmpty()) { plugin.message(sender, "info-noRegions"); } else { // First sort by type, then by name regions.sort((one, two) -> { int typeCompare = getTypeOrder(two).compareTo(getTypeOrder(one)); if (typeCompare != 0) { return typeCompare; } else { return one.getName().compareTo(two.getName()); } });// Header Message limitedToGroup = Message.empty(); if (filterGroup != null) { limitedToGroup = Message.fromKey("info-limitedToGroup").replacements(filterGroup.getName()); } plugin.message(sender, keyHeader, limitedToGroup); // Page entries int totalPages = ((int) (Math.ceil(regions.size() / ((double) (itemsPerPage)))));// Clip page to correct boundaries, not much need to tell the user if (regions.size() == (itemsPerPage + 1)) { // 19 total items is mapped to 1 page of 19 itemsPerPage++; totalPages = 1; } page = Math.max(1, Math.min(totalPages, page)); int linesPrinted = 1;// header for (int i = (page - 1) * itemsPerPage; (i < (page * itemsPerPage)) && (i < regions.size()); i++) { String v8; GeneralRegion region = regions.get(i); if (region.getType() == RegionType.RENT) { if (region.getOwner() == null) { v8 = "Forrent"; } else {v8 = "Rented"; } } else if (region.getOwner() == null) { v8 = "Forsale"; } else if (!((BuyRegion) (region)).isInResellingMode()) { v8 = "Sold"; } else {v8 = "Reselling"; } plugin.messageNoPrefix(sender, "info-entry" + v8, region); linesPrinted++; } Message footer = Message.empty(); // Previous button if (page > 1) { footer.append(Message.fromKey("info-pagePrevious").replacements((baseCommand + " ") + (page - 1))); } else { footer.append(Message.fromKey("info-pageNoPrevious")); } // Page status if (totalPages > 1) { StringBuilder pageString = new StringBuilder("" + page); for (int i = pageString.length(); i < (totalPages + "").length(); i++) { pageString.insert(0, "0"); } footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages));if (page < totalPages) { footer.append(Message.fromKey("info-pageNext").replacements((baseCommand + " ") + (page + 1))); } else { footer.append(Message.fromKey("info-pageNoNext")); } // Fill up space if the page is not full (aligns header nicely) for (int i = linesPrinted; i < (maximumItems - 1); i++) { sender.sendMessage(" ");} footer.send(sender); } } }
3.26
AreaShop_InfoCommand_getTypeOrder_rdh
/** * Get an integer to order by type, usable for Comparators. * * @param region * The region to get the order for * @return An integer for sorting by type */ private Integer getTypeOrder(GeneralRegion region) { if (region.getType() == RegionType.RENT) {if (region.getOwner() == null) { return 1; } else { return 2; } } else if (region.getOwner() == null) { return 3;} else if (!((BuyRegion) (region)).isInResellingMode()) { return 4; } else { return 5; } }
3.26
AreaShop_RentedRegionEvent_hasExtended_rdh
/** * Check if the region was extended or rented for the first time. * * @return true if the region was extended, false when rented for the first time */ public boolean hasExtended() { return extended; }
3.26
AreaShop_WorldGuardHandler6_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_SignsFeature_getSignLocations_rdh
/** * Get a list with all sign locations. * * @return A List with all sign locations */ public List<Location> getSignLocations() { List<Location> result = new ArrayList<>(); for (RegionSign sign : signs.values()) { result.add(sign.getLocation());} return result; }
3.26
AreaShop_SignsFeature_needsPeriodicUpdate_rdh
/** * Check if any of the signs need periodic updating. * * @return true if one or more of the signs need periodic updating, otherwise false */ public boolean needsPeriodicUpdate() { boolean result = false; for (RegionSign sign : signs.values()) { result |= sign.needsPeriodicUpdate(); } return result; }
3.26
AreaShop_SignsFeature_update_rdh
/** * Update all signs connected to this region. * * @return true if all signs are updated correctly, false if one or more updates failed */ public boolean update() { boolean result = true; for (RegionSign sign : signs.values()) { result &= sign.update(); } return result; }
3.26
AreaShop_SignsFeature_locationToString_rdh
/** * Convert a location to a string to use as map key. * * @param location * The location to get the key for * @return A string to use in a map for a location */ public static String locationToString(Location location) { return (((((location.getWorld().getName() + ";") + location.getBlockX()) + ";") + location.getBlockY()) + ";") + location.getBlockZ(); }
3.26
AreaShop_SignsFeature_getSignByLocation_rdh
/** * Get a sign by a location. * * @param location * The location to get the sign for * @return The RegionSign that is at the location, or null if none */ public static RegionSign getSignByLocation(Location location) { return allSigns.get(locationToString(location)); }
3.26
AreaShop_SignsFeature_getSignsRef_rdh
/** * Get the signs of this region. * * @return Map with signs: locationString -&gt; RegionSign */ Map<String, RegionSign> getSignsRef() { return signs; }
3.26
AreaShop_SignsFeature_getSignsByChunk_rdh
/** * Get the map with signs by chunk. * * @return Map with signs by chunk: chunkString -&gt; List&lt;RegionSign&gt; */ public static Map<String, List<RegionSign>> getSignsByChunk() { return signsByChunk; }
3.26
AreaShop_SignsFeature_chunkToString_rdh
/** * Convert a chunk to a string to use as map key. * Use a Location argument to prevent chunk loading! * * @param chunk * The location to get the key for * @return A string to use in a map for a chunk */ public static String chunkToString(Chunk chunk) { return (((chunk.getWorld().getName() + ";") + chunk.getX()) + ";") + chunk.getZ(); }
3.26
AreaShop_SignsFeature_getAllSigns_rdh
/** * Get the map with all signs. * * @return Map with all signs: locationString -&gt; RegionSign */ public static Map<String, RegionSign> getAllSigns() {return allSigns; }
3.26
AreaShop_SignsFeature_getSigns_rdh
/** * Get the signs of this region. * * @return List of signs */ public List<RegionSign> getSigns() { return Collections.unmodifiableList(new ArrayList<>(signs.values()));}
3.26
AreaShop_PlayerLoginLogoutListener_updateLastActive_rdh
/** * Update the last active time for all regions the player is owner off. * * @param player * The player to update the active times for */ private void updateLastActive(Player player) { for (GeneralRegion region : plugin.getFileManager().getRegions()) { if (region.isOwner(player)) { region.updateLastActiveTime(); } } }
3.26
AreaShop_PlayerLoginLogoutListener_onPlayerLogin_rdh
/** * Called when a sign is changed. * * @param event * The event */ @EventHandler(priority = EventPriority.MONITOR) public void onPlayerLogin(PlayerLoginEvent event) { if (event.getResult() != Result.ALLOWED) { return; } final Player player = event.getPlayer(); // Schedule task to check for notifications, prevents a lag spike at login Do.syncTimerLater(25, 25, () -> { // Delay until all regions are loaded if (!plugin.isReady()) { return true; } if (!player.isOnline()) { return false; } // Notify for rents that almost run out for (RentRegion region : plugin.getFileManager().getRents()) { if (region.isRenter(player)) { String warningSetting = region.getStringSetting("rent.warningOnLoginTime");if ((warningSetting == null) || warningSetting.isEmpty()) { continue; } long warningTime = Utils.durationStringToLong(warningSetting); if (region.getTimeLeft() < warningTime) { // Send the warning message later to let it appear after general MOTD messages AreaShop.getInstance().message(player, "rent-expireWarning", region); } } } // Notify admins for plugin updates AreaShop.getInstance().notifyUpdate(player); return false; }); // Check if the player has regions that use an old name of him and update them Do.syncTimerLater(22, 10, () -> { if (!plugin.isReady()) { return true; } List<GeneralRegion> regions = new ArrayList<>(); for (GeneralRegion region : plugin.getFileManager().getRegions()) { if (region.isOwner(player)) { regions.add(region); } } Do.forAll(plugin.getConfig().getInt("nameupdate.regionsPerTick"), regions, region -> { if (region instanceof BuyRegion) { if (!player.getName().equals(region.getStringSetting("buy.buyerName"))) { region.setSetting("buy.buyerName", player.getName()); region.update(); } } else if (region instanceof RentRegion) { if (!player.getName().equals(region.getStringSetting("rent.renterName"))) { region.setSetting("rent.renterName", player.getName()); region.update(); } } }); return false; });}
3.26
AreaShop_PlayerLoginLogoutListener_onPlayerLogout_rdh
// Active time updates @EventHandler(priority = EventPriority.MONITOR) public void onPlayerLogout(PlayerQuitEvent event) { updateLastActive(event.getPlayer()); }
3.26
AreaShop_FeatureManager_getRegionFeature_rdh
/** * Instanciate a feature for a certain region. * * @param region * The region to create a feature for * @param featureClazz * The class of the feature to create * @return The feature class */ public RegionFeature getRegionFeature(GeneralRegion region, Class<? extends RegionFeature> featureClazz) { try { return regionFeatureConstructors.get(featureClazz).newInstance(region); } catch (InstantiationException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { AreaShop.error("Failed to instantiate feature", featureClazz, "for region", region, e, e.getCause()); } return null; }
3.26
AreaShop_RentingRegionEvent_isExtending_rdh
/** * Check if the player is extending the region or renting it for the first time. * * @return true if the player tries to extend the region, false if he tries to rent it the first time */ public boolean isExtending() { return extending; }
3.26
AreaShop_RentingRegionEvent_getPlayer_rdh
/** * Get the player that is trying to rent the region. * * @return The player that is trying to rent the region */ public OfflinePlayer getPlayer() { return player; }
3.26
AreaShop_AddedFriendEvent_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_AddedFriendEvent_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_DelfriendCommand_canUse_rdh
/** * Check if a person can remove friends. * * @param person * The person to check * @param region * The region to check for * @return true if the person can remove friends, otherwise false */ public static boolean canUse(CommandSender person, GeneralRegion region) { if (person.hasPermission("areashop.delfriendall")) { return true; } if (person instanceof Player) {Player player = ((Player) (person)); return region.isOwner(player) && player.hasPermission("areashop.delfriend"); } return false; }
3.26
AreaShop_CommandManager_showHelp_rdh
/** * Shows the help page for the CommandSender. * * @param target * The CommandSender to show the help to */ public void showHelp(CommandSender target) { if (!target.hasPermission("areashop.help")) { plugin.message(target, "help-noPermission"); return; } // Add all messages to a list ArrayList<String> messages = new ArrayList<>(); plugin.message(target, "help-header"); plugin.message(target, "help-alias"); for (CommandAreaShop command : commands) { String help = command.getHelp(target); if ((help != null) && (!help.isEmpty())) { messages.add(help); } } // Send the messages to the target for (String message : messages) { plugin.messageNoPrefix(target, message); } }
3.26
AreaShop_CommandManager_getCommands_rdh
/** * Get the list with AreaShop commands. * * @return The list with AreaShop commands */ public List<CommandAreaShop> getCommands() { return commands; }
3.26