From 6a7258b692e9029532f5d57029fdf5f9a49e4296 Mon Sep 17 00:00:00 2001 From: Driftay Date: Sat, 24 Aug 2019 13:21:39 -0400 Subject: [PATCH] One Final Reformat --- .../integration/dynmap/DynmapStyle.java | 164 +- .../integration/dynmap/EngineDynmap.java | 1486 +++++----- .../integration/dynmap/TempAreaMarker.java | 170 +- .../integration/dynmap/TempMarker.java | 100 +- .../integration/dynmap/TempMarkerSet.java | 72 +- .../scoreboards/sidebar/FDefaultSidebar.java | 48 +- .../scoreboards/sidebar/FInfoSidebar.java | 34 +- .../player/PlayerChunkLocationExpression.java | 5 +- .../player/PlayerFactionExpression.java | 120 +- .../player/PlayerPowerExpression.java | 116 +- .../player/PlayerRoleExpression.java | 112 +- .../factions/zcore/fperms/Access.java | 64 +- .../zcore/fperms/DefaultPermissions.java | 301 +- .../factions/zcore/fperms/Permissable.java | 6 +- .../zcore/fperms/PermissableAction.java | 172 +- .../zcore/fupgrades/CropUpgrades.java | 96 +- .../factions/zcore/fupgrades/EXPUpgrade.java | 62 +- .../zcore/fupgrades/FUpgradesGUI.java | 7 +- .../zcore/fupgrades/SpawnerUpgrades.java | 50 +- .../factions/zcore/fupgrades/UpgradeType.java | 18 +- .../factions/zcore/nbtapi/NBTCompound.java | 290 +- .../factions/zcore/nbtapi/NBTContainer.java | 42 +- .../factions/zcore/nbtapi/NBTEntity.java | 20 +- .../factions/zcore/nbtapi/NBTFile.java | 58 +- .../factions/zcore/nbtapi/NBTItem.java | 44 +- .../factions/zcore/nbtapi/NBTList.java | 210 +- .../zcore/nbtapi/NBTListCompound.java | 164 +- .../zcore/nbtapi/NBTReflectionUtil.java | 1798 ++++++------ .../factions/zcore/nbtapi/NBTTileEntity.java | 20 +- .../factions/zcore/nbtapi/NBTType.java | 50 +- .../zcore/nbtapi/utils/GsonWrapper.java | 32 +- .../zcore/nbtapi/utils/MethodNames.java | 32 +- .../zcore/nbtapi/utils/MinecraftVersion.java | 90 +- .../factions/zcore/persist/MemoryBoard.java | 614 ++-- .../factions/zcore/persist/MemoryFPlayer.java | 2511 ++++++++--------- .../zcore/persist/MemoryFPlayers.java | 82 +- .../factions/zcore/persist/MemoryFaction.java | 7 +- .../zcore/persist/MemoryFactions.java | 278 +- .../factions/zcore/persist/SaveTask.java | 34 +- .../zcore/persist/json/FactionsJSON.java | 64 +- .../zcore/persist/json/JSONBoard.java | 136 +- .../zcore/persist/json/JSONFPlayer.java | 26 +- .../zcore/persist/json/JSONFPlayers.java | 288 +- .../zcore/persist/json/JSONFaction.java | 16 +- .../zcore/persist/json/JSONFactions.java | 386 +-- .../factions/zcore/util/DiscUtil.java | 172 +- .../factions/zcore/util/PermUtil.java | 98 +- .../factions/zcore/util/Persist.java | 210 +- .../factions/zcore/util/SmokeUtil.java | 88 +- .../factions/zcore/util/TagReplacer.java | 542 ++-- .../factions/zcore/util/TagUtil.java | 512 ++-- .../factions/zcore/util/TextUtil.java | 366 +-- .../factions/zcore/util/UUIDFetcher.java | 140 +- 53 files changed, 6311 insertions(+), 6312 deletions(-) diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java b/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java index 239b04e8..7fb28c15 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java @@ -3,105 +3,105 @@ package com.massivecraft.factions.integration.dynmap; import com.massivecraft.factions.Conf; public class DynmapStyle { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String lineColor = null; - public Double lineOpacity = null; - public Integer lineWeight = null; - public String fillColor = null; - public Double fillOpacity = null; - // NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. - // The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that. - // Using dynmap is optional. - public String homeMarker = null; - public Boolean boost = null; + public String lineColor = null; + public Double lineOpacity = null; + public Integer lineWeight = null; + public String fillColor = null; + public Double fillOpacity = null; + // NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. + // The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that. + // Using dynmap is optional. + public String homeMarker = null; + public Boolean boost = null; - @SafeVarargs - public static T coalesce(T... items) { - for (T item : items) { - if (item != null) { - return item; - } - } - return null; - } + @SafeVarargs + public static T coalesce(T... items) { + for (T item : items) { + if (item != null) { + return item; + } + } + return null; + } - public static int getColor(String string) { - int ret = 0x00FF00; - try { - ret = Integer.parseInt(string.substring(1), 16); - } catch (NumberFormatException ignored) { - } - return ret; - } + public static int getColor(String string) { + int ret = 0x00FF00; + try { + ret = Integer.parseInt(string.substring(1), 16); + } catch (NumberFormatException ignored) { + } + return ret; + } - public int getLineColor() { - return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR)); - } + public int getLineColor() { + return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR)); + } - public DynmapStyle setStrokeColor(String strokeColor) { - this.lineColor = strokeColor; - return this; - } + public DynmapStyle setStrokeColor(String strokeColor) { + this.lineColor = strokeColor; + return this; + } - public double getLineOpacity() { - return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY); - } + public double getLineOpacity() { + return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY); + } - public DynmapStyle setLineOpacity(Double strokeOpacity) { - this.lineOpacity = strokeOpacity; - return this; - } + public DynmapStyle setLineOpacity(Double strokeOpacity) { + this.lineOpacity = strokeOpacity; + return this; + } - public int getLineWeight() { - return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT); - } + public int getLineWeight() { + return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT); + } - public DynmapStyle setLineWeight(Integer strokeWeight) { - this.lineWeight = strokeWeight; - return this; - } + public DynmapStyle setLineWeight(Integer strokeWeight) { + this.lineWeight = strokeWeight; + return this; + } - public int getFillColor() { - return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR)); - } + public int getFillColor() { + return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR)); + } - public DynmapStyle setFillColor(String fillColor) { - this.fillColor = fillColor; - return this; - } + public DynmapStyle setFillColor(String fillColor) { + this.fillColor = fillColor; + return this; + } - public double getFillOpacity() { - return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY); - } + public double getFillOpacity() { + return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY); + } - public DynmapStyle setFillOpacity(Double fillOpacity) { - this.fillOpacity = fillOpacity; - return this; - } + public DynmapStyle setFillOpacity(Double fillOpacity) { + this.fillOpacity = fillOpacity; + return this; + } - public String getHomeMarker() { - return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER); - } + public String getHomeMarker() { + return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER); + } - public DynmapStyle setHomeMarker(String homeMarker) { - this.homeMarker = homeMarker; - return this; - } + public DynmapStyle setHomeMarker(String homeMarker) { + this.homeMarker = homeMarker; + return this; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public boolean getBoost() { - return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST); - } + public boolean getBoost() { + return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST); + } - public DynmapStyle setBoost(Boolean boost) { - this.boost = boost; - return this; - } + public DynmapStyle setBoost(Boolean boost) { + this.boost = boost; + return this; + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java index 62264fe9..a4774969 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java @@ -17,747 +17,747 @@ import java.util.Map.Entry; // This source code is a heavily modified version of mikeprimms plugin Dynmap-Factions. public class EngineDynmap { - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // - - public final static int BLOCKS_PER_CHUNK = 16; - - public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; - - public final static String FACTIONS = "factions"; - public final static String FACTIONS_ = FACTIONS + "_"; - - public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; - - public final static String FACTIONS_HOME = FACTIONS_ + "home"; - public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; - - public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; - public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; - - // -------------------------------------------- // - // INSTANCE & CONSTRUCT - // -------------------------------------------- // - - private static final EngineDynmap i = new EngineDynmap(); - public DynmapAPI dynmapApi; - public MarkerAPI markerApi; - public MarkerSet markerset; - - private EngineDynmap() { - } - - public static EngineDynmap getInstance() { - return i; - } - - public static String getHtmlPlayerString(Collection playersOfficersList) { - StringBuilder ret = new StringBuilder(); - for (FPlayer fplayer : playersOfficersList) { - if (ret.length() > 0) { - ret.append(", "); - } - ret.append(getHtmlPlayerName(fplayer)); - } - return ret.toString(); - } - - public static String getHtmlPlayerName(FPlayer fplayer) { - return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; - } - - public static String escapeHtml(String string) { - StringBuilder out = new StringBuilder(Math.max(16, string.length())); - for (int i = 0; i < string.length(); i++) { - char c = string.charAt(i); - if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { - out.append("&#") - .append((int) c) - .append(';'); - } else { - out.append(c); - } - } - return out.toString(); - } - - // Thread Safe / Asynchronous: Yes - public static void info(String msg) { - System.out.println(DYNMAP_INTEGRATION + msg); - } - - // -------------------------------------------- // - // UPDATE: HOMES - // -------------------------------------------- // - - // Thread Safe / Asynchronous: Yes - public static void severe(String msg) { - System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); - } - - public void init() { - Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - - if (dynmap == null || !dynmap.isEnabled()) { - return; - } - - // Should we even use dynmap? - if (!Conf.dynmapUse) { - if (this.markerset != null) { - this.markerset.deleteMarkerSet(); - this.markerset = null; - } - return; - } - - // Shedule non thread safe sync at the end! - Bukkit.getScheduler().scheduleSyncRepeatingTask(P.p, () -> { - - final Map homes = createHomes(); - final Map areas = createAreas(); - final Map> playerSets = createPlayersets(); - - if (!updateCore()) { - return; - } - - // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. - if (!updateLayer(createLayer())) { - return; - } - - updateHomes(homes); - updateAreas(areas); - updatePlayersets(playerSets); - }, 100L, 100L); - } - - // -------------------------------------------- // - // UPDATE: AREAS - // -------------------------------------------- // - - // Thread Safe / Asynchronous: No - public boolean updateCore() { - // Get DynmapAPI - this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); - if (this.dynmapApi == null) { - severe("Could not retrieve the DynmapAPI."); - return false; - } - - // Get MarkerAPI - this.markerApi = this.dynmapApi.getMarkerAPI(); - if (this.markerApi == null) { - severe("Could not retrieve the MarkerAPI."); - return false; - } - - return true; - } - - // Thread Safe / Asynchronous: Yes - public TempMarkerSet createLayer() { - TempMarkerSet ret = new TempMarkerSet(); - ret.label = Conf.dynmapLayerName; - ret.minimumZoom = Conf.dynmapLayerMinimumZoom; - ret.priority = Conf.dynmapLayerPriority; - ret.hideByDefault = !Conf.dynmapLayerVisible; - return ret; - } - - // Thread Safe / Asynchronous: No - public boolean updateLayer(TempMarkerSet temp) { - this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); - if (this.markerset == null) { - this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); - if (this.markerset == null) { - severe("Could not create the Faction Markerset/Layer"); - return false; - } - } else { - temp.update(this.markerset); - } - return true; - } - - // Thread Safe / Asynchronous: Yes - public Map createHomes() { - Map ret = new HashMap<>(); - - // Loop current factions - for (Faction faction : Factions.getInstance().getAllFactions()) { - Location ps = faction.getHome(); - if (ps == null) { - continue; - } - - DynmapStyle style = getStyle(faction); - - String markerId = FACTIONS_HOME_ + faction.getId(); - - TempMarker temp = new TempMarker(); - temp.label = ChatColor.stripColor(faction.getTag()); - temp.world = ps.getWorld().toString(); - temp.x = ps.getX(); - temp.y = ps.getY(); - temp.z = ps.getZ(); - temp.iconName = style.getHomeMarker(); - temp.description = getDescription(faction); - - ret.put(markerId, temp); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - // This method places out the faction home markers into the factions markerset. - public void updateHomes(Map homes) { - // Put all current faction markers in a map - Map markers = new HashMap<>(); - for (Marker marker : this.markerset.getMarkers()) { - markers.put(marker.getMarkerID(), marker); - } - - // Loop homes - for (Entry entry : homes.entrySet()) { - String markerId = entry.getKey(); - TempMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - Marker marker = markers.remove(markerId); - if (marker == null) { - marker = temp.create(this.markerApi, this.markerset, markerId); - if (marker == null) { - EngineDynmap.severe("Could not get/create the home marker " + markerId); - } - } else { - temp.update(this.markerApi, marker); - } - } - - // Delete Deprecated Markers - // Only old markers should now be left - for (Marker marker : markers.values()) { - marker.deleteMarker(); - } - } - - // -------------------------------------------- // - // UPDATE: PLAYERSET - // -------------------------------------------- // - - // Thread Safe: YES - public Map createAreas() { - Map>> worldFactionChunks = createWorldFactionChunks(); - return createAreas(worldFactionChunks); - } - - // Thread Safe: YES - public Map>> createWorldFactionChunks() { - // Create map "world name --> faction --> set of chunk coords" - Map>> worldFactionChunks = new HashMap<>(); - - // Note: The board is the world. The board id is the world name. - MemoryBoard board = (MemoryBoard) Board.getInstance(); - - for (Entry entry : board.flocationIds.entrySet()) { - String world = entry.getKey().getWorldName(); - Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); - - Map> factionChunks = worldFactionChunks.get(world); - if (factionChunks == null) { - factionChunks = new HashMap<>(); - worldFactionChunks.put(world, factionChunks); - } - - Set factionTerritory = factionChunks.get(chunkOwner); - if (factionTerritory == null) { - factionTerritory = new HashSet<>(); - factionChunks.put(chunkOwner, factionTerritory); - } - - factionTerritory.add(entry.getKey()); - } - - return worldFactionChunks; - } - - // Thread Safe: YES - public Map createAreas(Map>> worldFactionChunks) { - Map ret = new HashMap<>(); - - // For each world - for (Entry>> entry : worldFactionChunks.entrySet()) { - String world = entry.getKey(); - Map> factionChunks = entry.getValue(); - - // For each faction and its chunks in that world - for (Entry> entry1 : factionChunks.entrySet()) { - Faction faction = entry1.getKey(); - Set chunks = entry1.getValue(); - Map worldFactionMarkers = createAreas(world, faction, chunks); - ret.putAll(worldFactionMarkers); - } - } - - return ret; - } - - // Thread Safe: YES - // Handle specific faction on specific world - // "handle faction on world" - public Map createAreas(String world, Faction faction, Set chunks) { - Map ret = new HashMap<>(); - - // If the faction is visible ... - if (!isVisible(faction, world)) { - return ret; - } - - // ... and has any chunks ... - if (chunks.isEmpty()) { - return ret; - } - - // Index of polygon for given faction - int markerIndex = 0; - - // Create the info window - String description = getDescription(faction); - - // Fetch Style - DynmapStyle style = this.getStyle(faction); - - // Loop through chunks: set flags on chunk map - TileFlags allChunkFlags = new TileFlags(); - LinkedList allChunks = new LinkedList<>(); - for (FLocation chunk : chunks) { - allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk - allChunks.addLast(chunk); - } - - // Loop through until we don't find more areas - while (allChunks != null) { - TileFlags ourChunkFlags = null; - LinkedList ourChunks = null; - LinkedList newChunks = null; - - int minimumX = Integer.MAX_VALUE; - int minimumZ = Integer.MAX_VALUE; - for (FLocation chunk : allChunks) { - int chunkX = (int) chunk.getX(); - int chunkZ = (int) chunk.getZ(); - - // If we need to start shape, and this block is not part of one yet - if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) { - ourChunkFlags = new TileFlags(); // Create map for shape - ourChunks = new LinkedList<>(); - floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape - ourChunks.add(chunk); // Add it to our chunk list - minimumX = chunkX; - minimumZ = chunkZ; - } - // If shape found, and we're in it, add to our node list - else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { - ourChunks.add(chunk); - if (chunkX < minimumX) { - minimumX = chunkX; - minimumZ = chunkZ; - } else if (chunkX == minimumX && chunkZ < minimumZ) { - minimumZ = chunkZ; - } - } - // Else, keep it in the list for the next polygon - else { - if (newChunks == null) { - newChunks = new LinkedList<>(); - } - newChunks.add(chunk); - } - } - - // Replace list (null if no more to process) - allChunks = newChunks; - - if (ourChunkFlags == null) { - continue; - } - - // Trace outline of blocks - start from minx, minz going to x+ - int initialX = minimumX; - int initialZ = minimumZ; - int currentX = minimumX; - int currentZ = minimumZ; - Direction direction = Direction.XPLUS; - ArrayList linelist = new ArrayList<>(); - linelist.add(new int[]{initialX, initialZ}); // Add start point - while ((currentX != initialX) || (currentZ != initialZ) || (direction != Direction.ZMINUS)) { - switch (direction) { - case XPLUS: // Segment in X+ direction - if (!ourChunkFlags.getFlag(currentX + 1, currentZ)) { // Right turn? - linelist.add(new int[]{currentX + 1, currentZ}); // Finish line - direction = Direction.ZPLUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ - 1)) { // Straight? - currentX++; - } else { // Left turn - linelist.add(new int[]{currentX + 1, currentZ}); // Finish line - direction = Direction.ZMINUS; - currentX++; - currentZ--; - } - break; - case ZPLUS: // Segment in Z+ direction - if (!ourChunkFlags.getFlag(currentX, currentZ + 1)) { // Right turn? - linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line - direction = Direction.XMINUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ + 1)) { // Straight? - currentZ++; - } else { // Left turn - linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line - direction = Direction.XPLUS; - currentX++; - currentZ++; - } - break; - case XMINUS: // Segment in X- direction - if (!ourChunkFlags.getFlag(currentX - 1, currentZ)) { // Right turn? - linelist.add(new int[]{currentX, currentZ + 1}); // Finish line - direction = Direction.ZMINUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ + 1)) { // Straight? - currentX--; - } else { // Left turn - linelist.add(new int[]{currentX, currentZ + 1}); // Finish line - direction = Direction.ZPLUS; - currentX--; - currentZ++; - } - break; - case ZMINUS: // Segment in Z- direction - if (!ourChunkFlags.getFlag(currentX, currentZ - 1)) { // Right turn? - linelist.add(new int[]{currentX, currentZ}); // Finish line - direction = Direction.XPLUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ - 1)) { // Straight? - currentZ--; - } else { // Left turn - linelist.add(new int[]{currentX, currentZ}); // Finish line - direction = Direction.XMINUS; - currentX--; - currentZ--; - } - break; - } - } - - int sz = linelist.size(); - double[] x = new double[sz]; - double[] z = new double[sz]; - for (int i = 0; i < sz; i++) { - int[] line = linelist.get(i); - x[i] = (double) line[0] * (double) BLOCKS_PER_CHUNK; - z[i] = (double) line[1] * (double) BLOCKS_PER_CHUNK; - } - - // Build information for specific area - String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; - - TempAreaMarker temp = new TempAreaMarker(); - temp.label = faction.getTag(); - temp.world = world; - temp.x = x; - temp.z = z; - temp.description = description; - - temp.lineColor = style.getLineColor(); - temp.lineOpacity = style.getLineOpacity(); - temp.lineWeight = style.getLineWeight(); - - temp.fillColor = style.getFillColor(); - temp.fillOpacity = style.getFillOpacity(); - - temp.boost = style.getBoost(); - - ret.put(markerId, temp); - - markerIndex++; - } - - return ret; - } - - // -------------------------------------------- // - // UTIL & SHARED - // -------------------------------------------- // - - // Thread Safe: NO - public void updateAreas(Map areas) { - // Map Current - Map markers = new HashMap<>(); - for (AreaMarker marker : this.markerset.getAreaMarkers()) { - markers.put(marker.getMarkerID(), marker); - } - - // Loop New - for (Entry entry : areas.entrySet()) { - String markerId = entry.getKey(); - TempAreaMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - AreaMarker marker = markers.remove(markerId); - if (marker == null) { - marker = temp.create(this.markerset, markerId); - if (marker == null) { - severe("Could not get/create the area marker " + markerId); - } - } else { - temp.update(marker); - } - } - - // Only old/outdated should now be left. Delete them. - for (AreaMarker marker : markers.values()) { - marker.deleteMarker(); - } - } - - // Thread Safe / Asynchronous: Yes - public String createPlayersetId(Faction faction) { - if (faction == null) { - return null; - } - if (faction.isWilderness()) { - return null; - } - String factionId = faction.getId(); - if (factionId == null) { - return null; - } - return FACTIONS_PLAYERSET_ + factionId; - } - - // Thread Safe / Asynchronous: Yes - public Set createPlayerset(Faction faction) { - if (faction == null) { - return null; - } - if (faction.isWilderness()) { - return null; - } - - Set ret = new HashSet<>(); - - for (FPlayer fplayer : faction.getFPlayers()) { - // NOTE: We add both UUID and name. This might be a good idea for future proofing. - ret.add(fplayer.getId()); - ret.add(fplayer.getName()); - } - - return ret; - } - - // Thread Safe / Asynchronous: Yes - public Map> createPlayersets() { - if (!Conf.dynmapVisibilityByFaction) { - return null; - } - - Map> ret = new HashMap<>(); - - for (Faction faction : Factions.getInstance().getAllFactions()) { - String playersetId = createPlayersetId(faction); - if (playersetId == null) { - continue; - } - Set playerIds = createPlayerset(faction); - if (playerIds == null) { - continue; - } - ret.put(playersetId, playerIds); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - public void updatePlayersets(Map> playersets) { - if (playersets == null) { - return; - } - - // Remove - for (PlayerSet set : this.markerApi.getPlayerSets()) { - if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { - continue; - } - - // (Null means remove all) - if (playersets.containsKey(set.getSetID())) { - continue; - } - - set.deleteSet(); - } - - // Add / Update - for (Entry> entry : playersets.entrySet()) { - // Extract from Entry - String setId = entry.getKey(); - Set playerIds = entry.getValue(); - - // Get Creatively - PlayerSet set = this.markerApi.getPlayerSet(setId); - if (set == null) { - set = this.markerApi.createPlayerSet(setId, // id - true, // symmetric - playerIds, // players - false // persistent - ); - } - if (set == null) { - severe("Could not get/create the player set " + setId); - continue; - } - - // Set Content - set.setPlayers(playerIds); - } - } - - // Thread Safe / Asynchronous: Yes - private String getDescription(Faction faction) { - String ret = "
" + Conf.dynmapDescription + "
"; - - // Name - String name = faction.getTag(); - name = escapeHtml(ChatColor.stripColor(name)); - ret = ret.replace("%name%", name); - - // Description - String description = faction.getDescription(); - description = escapeHtml(ChatColor.stripColor(description)); - ret = ret.replace("%description%", description); - - // Money - - String money = "unavailable"; - if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) - money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); - ret = ret.replace("%money%", money); - - - // Players - Set playersList = faction.getFPlayers(); - String playersCount = String.valueOf(playersList.size()); - String players = getHtmlPlayerString(playersList); - - FPlayer playersLeaderObject = faction.getFPlayerAdmin(); - String playersLeader = getHtmlPlayerName(playersLeaderObject); - - ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); - String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); - String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); - - ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); - String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); - String playersModerators = getHtmlPlayerString(playersModeratorsList); - - - ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); - String playersNormalsCount = String.valueOf(playersNormalsList.size()); - String playersNormals = getHtmlPlayerString(playersNormalsList); - - ret = ret.replace("%players%", players); - ret = ret.replace("%players.count%", playersCount); - ret = ret.replace("%players.leader%", playersLeader); - ret = ret.replace("%players.admins%", playersCoAdmins); - ret = ret.replace("%players.admins.count%", playersCoAdminsCount); - ret = ret.replace("%players.moderators%", playersModerators); - ret = ret.replace("%players.moderators.count%", playersModeratorsCount); - ret = ret.replace("%players.normals%", playersNormals); - ret = ret.replace("%players.normals.count%", playersNormalsCount); - - return ret; - } - - // Thread Safe / Asynchronous: Yes - private boolean isVisible(Faction faction, String world) { - if (faction == null) { - return false; - } - final String factionId = faction.getId(); - if (factionId == null) { - return false; - } - final String factionName = faction.getTag(); - if (factionName == null) { - return false; - } - - Set visible = Conf.dynmapVisibleFactions; - Set hidden = Conf.dynmapHiddenFactions; - - if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { - return false; - } - - return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); - } - - // Thread Safe / Asynchronous: Yes - public DynmapStyle getStyle(Faction faction) { - DynmapStyle ret; - - ret = Conf.dynmapFactionStyles.get(faction.getId()); - if (ret != null) { - return ret; - } - - ret = Conf.dynmapFactionStyles.get(faction.getTag()); - if (ret != null) { - return ret; - } - - return Conf.dynmapDefaultStyle; - } - - // Find all contiguous blocks, set in target and clear in source - private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { - int cnt = 0; - ArrayDeque stack = new ArrayDeque<>(); - stack.push(new int[]{x, y}); - - while (!stack.isEmpty()) { - int[] nxt = stack.pop(); - x = nxt[0]; - y = nxt[1]; - if (source.getFlag(x, y)) { // Set in src - source.setFlag(x, y, false); // Clear source - destination.setFlag(x, y, true); // Set in destination - cnt++; - if (source.getFlag(x + 1, y)) { - stack.push(new int[]{x + 1, y}); - } - if (source.getFlag(x - 1, y)) { - stack.push(new int[]{x - 1, y}); - } - if (source.getFlag(x, y + 1)) { - stack.push(new int[]{x, y + 1}); - } - if (source.getFlag(x, y - 1)) { - stack.push(new int[]{x, y - 1}); - } - } - } - return cnt; - } - - enum Direction { - XPLUS, ZPLUS, XMINUS, ZMINUS - } + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // + + public final static int BLOCKS_PER_CHUNK = 16; + + public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; + + public final static String FACTIONS = "factions"; + public final static String FACTIONS_ = FACTIONS + "_"; + + public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; + + public final static String FACTIONS_HOME = FACTIONS_ + "home"; + public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; + + public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; + public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; + + // -------------------------------------------- // + // INSTANCE & CONSTRUCT + // -------------------------------------------- // + + private static final EngineDynmap i = new EngineDynmap(); + public DynmapAPI dynmapApi; + public MarkerAPI markerApi; + public MarkerSet markerset; + + private EngineDynmap() { + } + + public static EngineDynmap getInstance() { + return i; + } + + public static String getHtmlPlayerString(Collection playersOfficersList) { + StringBuilder ret = new StringBuilder(); + for (FPlayer fplayer : playersOfficersList) { + if (ret.length() > 0) { + ret.append(", "); + } + ret.append(getHtmlPlayerName(fplayer)); + } + return ret.toString(); + } + + public static String getHtmlPlayerName(FPlayer fplayer) { + return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; + } + + public static String escapeHtml(String string) { + StringBuilder out = new StringBuilder(Math.max(16, string.length())); + for (int i = 0; i < string.length(); i++) { + char c = string.charAt(i); + if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { + out.append("&#") + .append((int) c) + .append(';'); + } else { + out.append(c); + } + } + return out.toString(); + } + + // Thread Safe / Asynchronous: Yes + public static void info(String msg) { + System.out.println(DYNMAP_INTEGRATION + msg); + } + + // -------------------------------------------- // + // UPDATE: HOMES + // -------------------------------------------- // + + // Thread Safe / Asynchronous: Yes + public static void severe(String msg) { + System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); + } + + public void init() { + Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + + if (dynmap == null || !dynmap.isEnabled()) { + return; + } + + // Should we even use dynmap? + if (!Conf.dynmapUse) { + if (this.markerset != null) { + this.markerset.deleteMarkerSet(); + this.markerset = null; + } + return; + } + + // Shedule non thread safe sync at the end! + Bukkit.getScheduler().scheduleSyncRepeatingTask(P.p, () -> { + + final Map homes = createHomes(); + final Map areas = createAreas(); + final Map> playerSets = createPlayersets(); + + if (!updateCore()) { + return; + } + + // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. + if (!updateLayer(createLayer())) { + return; + } + + updateHomes(homes); + updateAreas(areas); + updatePlayersets(playerSets); + }, 100L, 100L); + } + + // -------------------------------------------- // + // UPDATE: AREAS + // -------------------------------------------- // + + // Thread Safe / Asynchronous: No + public boolean updateCore() { + // Get DynmapAPI + this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); + if (this.dynmapApi == null) { + severe("Could not retrieve the DynmapAPI."); + return false; + } + + // Get MarkerAPI + this.markerApi = this.dynmapApi.getMarkerAPI(); + if (this.markerApi == null) { + severe("Could not retrieve the MarkerAPI."); + return false; + } + + return true; + } + + // Thread Safe / Asynchronous: Yes + public TempMarkerSet createLayer() { + TempMarkerSet ret = new TempMarkerSet(); + ret.label = Conf.dynmapLayerName; + ret.minimumZoom = Conf.dynmapLayerMinimumZoom; + ret.priority = Conf.dynmapLayerPriority; + ret.hideByDefault = !Conf.dynmapLayerVisible; + return ret; + } + + // Thread Safe / Asynchronous: No + public boolean updateLayer(TempMarkerSet temp) { + this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); + if (this.markerset == null) { + this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); + if (this.markerset == null) { + severe("Could not create the Faction Markerset/Layer"); + return false; + } + } else { + temp.update(this.markerset); + } + return true; + } + + // Thread Safe / Asynchronous: Yes + public Map createHomes() { + Map ret = new HashMap<>(); + + // Loop current factions + for (Faction faction : Factions.getInstance().getAllFactions()) { + Location ps = faction.getHome(); + if (ps == null) { + continue; + } + + DynmapStyle style = getStyle(faction); + + String markerId = FACTIONS_HOME_ + faction.getId(); + + TempMarker temp = new TempMarker(); + temp.label = ChatColor.stripColor(faction.getTag()); + temp.world = ps.getWorld().toString(); + temp.x = ps.getX(); + temp.y = ps.getY(); + temp.z = ps.getZ(); + temp.iconName = style.getHomeMarker(); + temp.description = getDescription(faction); + + ret.put(markerId, temp); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + // This method places out the faction home markers into the factions markerset. + public void updateHomes(Map homes) { + // Put all current faction markers in a map + Map markers = new HashMap<>(); + for (Marker marker : this.markerset.getMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop homes + for (Entry entry : homes.entrySet()) { + String markerId = entry.getKey(); + TempMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + Marker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerApi, this.markerset, markerId); + if (marker == null) { + EngineDynmap.severe("Could not get/create the home marker " + markerId); + } + } else { + temp.update(this.markerApi, marker); + } + } + + // Delete Deprecated Markers + // Only old markers should now be left + for (Marker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // -------------------------------------------- // + // UPDATE: PLAYERSET + // -------------------------------------------- // + + // Thread Safe: YES + public Map createAreas() { + Map>> worldFactionChunks = createWorldFactionChunks(); + return createAreas(worldFactionChunks); + } + + // Thread Safe: YES + public Map>> createWorldFactionChunks() { + // Create map "world name --> faction --> set of chunk coords" + Map>> worldFactionChunks = new HashMap<>(); + + // Note: The board is the world. The board id is the world name. + MemoryBoard board = (MemoryBoard) Board.getInstance(); + + for (Entry entry : board.flocationIds.entrySet()) { + String world = entry.getKey().getWorldName(); + Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); + + Map> factionChunks = worldFactionChunks.get(world); + if (factionChunks == null) { + factionChunks = new HashMap<>(); + worldFactionChunks.put(world, factionChunks); + } + + Set factionTerritory = factionChunks.get(chunkOwner); + if (factionTerritory == null) { + factionTerritory = new HashSet<>(); + factionChunks.put(chunkOwner, factionTerritory); + } + + factionTerritory.add(entry.getKey()); + } + + return worldFactionChunks; + } + + // Thread Safe: YES + public Map createAreas(Map>> worldFactionChunks) { + Map ret = new HashMap<>(); + + // For each world + for (Entry>> entry : worldFactionChunks.entrySet()) { + String world = entry.getKey(); + Map> factionChunks = entry.getValue(); + + // For each faction and its chunks in that world + for (Entry> entry1 : factionChunks.entrySet()) { + Faction faction = entry1.getKey(); + Set chunks = entry1.getValue(); + Map worldFactionMarkers = createAreas(world, faction, chunks); + ret.putAll(worldFactionMarkers); + } + } + + return ret; + } + + // Thread Safe: YES + // Handle specific faction on specific world + // "handle faction on world" + public Map createAreas(String world, Faction faction, Set chunks) { + Map ret = new HashMap<>(); + + // If the faction is visible ... + if (!isVisible(faction, world)) { + return ret; + } + + // ... and has any chunks ... + if (chunks.isEmpty()) { + return ret; + } + + // Index of polygon for given faction + int markerIndex = 0; + + // Create the info window + String description = getDescription(faction); + + // Fetch Style + DynmapStyle style = this.getStyle(faction); + + // Loop through chunks: set flags on chunk map + TileFlags allChunkFlags = new TileFlags(); + LinkedList allChunks = new LinkedList<>(); + for (FLocation chunk : chunks) { + allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk + allChunks.addLast(chunk); + } + + // Loop through until we don't find more areas + while (allChunks != null) { + TileFlags ourChunkFlags = null; + LinkedList ourChunks = null; + LinkedList newChunks = null; + + int minimumX = Integer.MAX_VALUE; + int minimumZ = Integer.MAX_VALUE; + for (FLocation chunk : allChunks) { + int chunkX = (int) chunk.getX(); + int chunkZ = (int) chunk.getZ(); + + // If we need to start shape, and this block is not part of one yet + if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunkFlags = new TileFlags(); // Create map for shape + ourChunks = new LinkedList<>(); + floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape + ourChunks.add(chunk); // Add it to our chunk list + minimumX = chunkX; + minimumZ = chunkZ; + } + // If shape found, and we're in it, add to our node list + else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunks.add(chunk); + if (chunkX < minimumX) { + minimumX = chunkX; + minimumZ = chunkZ; + } else if (chunkX == minimumX && chunkZ < minimumZ) { + minimumZ = chunkZ; + } + } + // Else, keep it in the list for the next polygon + else { + if (newChunks == null) { + newChunks = new LinkedList<>(); + } + newChunks.add(chunk); + } + } + + // Replace list (null if no more to process) + allChunks = newChunks; + + if (ourChunkFlags == null) { + continue; + } + + // Trace outline of blocks - start from minx, minz going to x+ + int initialX = minimumX; + int initialZ = minimumZ; + int currentX = minimumX; + int currentZ = minimumZ; + Direction direction = Direction.XPLUS; + ArrayList linelist = new ArrayList<>(); + linelist.add(new int[]{initialX, initialZ}); // Add start point + while ((currentX != initialX) || (currentZ != initialZ) || (direction != Direction.ZMINUS)) { + switch (direction) { + case XPLUS: // Segment in X+ direction + if (!ourChunkFlags.getFlag(currentX + 1, currentZ)) { // Right turn? + linelist.add(new int[]{currentX + 1, currentZ}); // Finish line + direction = Direction.ZPLUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ - 1)) { // Straight? + currentX++; + } else { // Left turn + linelist.add(new int[]{currentX + 1, currentZ}); // Finish line + direction = Direction.ZMINUS; + currentX++; + currentZ--; + } + break; + case ZPLUS: // Segment in Z+ direction + if (!ourChunkFlags.getFlag(currentX, currentZ + 1)) { // Right turn? + linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line + direction = Direction.XMINUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ + 1)) { // Straight? + currentZ++; + } else { // Left turn + linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line + direction = Direction.XPLUS; + currentX++; + currentZ++; + } + break; + case XMINUS: // Segment in X- direction + if (!ourChunkFlags.getFlag(currentX - 1, currentZ)) { // Right turn? + linelist.add(new int[]{currentX, currentZ + 1}); // Finish line + direction = Direction.ZMINUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ + 1)) { // Straight? + currentX--; + } else { // Left turn + linelist.add(new int[]{currentX, currentZ + 1}); // Finish line + direction = Direction.ZPLUS; + currentX--; + currentZ++; + } + break; + case ZMINUS: // Segment in Z- direction + if (!ourChunkFlags.getFlag(currentX, currentZ - 1)) { // Right turn? + linelist.add(new int[]{currentX, currentZ}); // Finish line + direction = Direction.XPLUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ - 1)) { // Straight? + currentZ--; + } else { // Left turn + linelist.add(new int[]{currentX, currentZ}); // Finish line + direction = Direction.XMINUS; + currentX--; + currentZ--; + } + break; + } + } + + int sz = linelist.size(); + double[] x = new double[sz]; + double[] z = new double[sz]; + for (int i = 0; i < sz; i++) { + int[] line = linelist.get(i); + x[i] = (double) line[0] * (double) BLOCKS_PER_CHUNK; + z[i] = (double) line[1] * (double) BLOCKS_PER_CHUNK; + } + + // Build information for specific area + String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; + + TempAreaMarker temp = new TempAreaMarker(); + temp.label = faction.getTag(); + temp.world = world; + temp.x = x; + temp.z = z; + temp.description = description; + + temp.lineColor = style.getLineColor(); + temp.lineOpacity = style.getLineOpacity(); + temp.lineWeight = style.getLineWeight(); + + temp.fillColor = style.getFillColor(); + temp.fillOpacity = style.getFillOpacity(); + + temp.boost = style.getBoost(); + + ret.put(markerId, temp); + + markerIndex++; + } + + return ret; + } + + // -------------------------------------------- // + // UTIL & SHARED + // -------------------------------------------- // + + // Thread Safe: NO + public void updateAreas(Map areas) { + // Map Current + Map markers = new HashMap<>(); + for (AreaMarker marker : this.markerset.getAreaMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop New + for (Entry entry : areas.entrySet()) { + String markerId = entry.getKey(); + TempAreaMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + AreaMarker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerset, markerId); + if (marker == null) { + severe("Could not get/create the area marker " + markerId); + } + } else { + temp.update(marker); + } + } + + // Only old/outdated should now be left. Delete them. + for (AreaMarker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // Thread Safe / Asynchronous: Yes + public String createPlayersetId(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + String factionId = faction.getId(); + if (factionId == null) { + return null; + } + return FACTIONS_PLAYERSET_ + factionId; + } + + // Thread Safe / Asynchronous: Yes + public Set createPlayerset(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + + Set ret = new HashSet<>(); + + for (FPlayer fplayer : faction.getFPlayers()) { + // NOTE: We add both UUID and name. This might be a good idea for future proofing. + ret.add(fplayer.getId()); + ret.add(fplayer.getName()); + } + + return ret; + } + + // Thread Safe / Asynchronous: Yes + public Map> createPlayersets() { + if (!Conf.dynmapVisibilityByFaction) { + return null; + } + + Map> ret = new HashMap<>(); + + for (Faction faction : Factions.getInstance().getAllFactions()) { + String playersetId = createPlayersetId(faction); + if (playersetId == null) { + continue; + } + Set playerIds = createPlayerset(faction); + if (playerIds == null) { + continue; + } + ret.put(playersetId, playerIds); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + public void updatePlayersets(Map> playersets) { + if (playersets == null) { + return; + } + + // Remove + for (PlayerSet set : this.markerApi.getPlayerSets()) { + if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { + continue; + } + + // (Null means remove all) + if (playersets.containsKey(set.getSetID())) { + continue; + } + + set.deleteSet(); + } + + // Add / Update + for (Entry> entry : playersets.entrySet()) { + // Extract from Entry + String setId = entry.getKey(); + Set playerIds = entry.getValue(); + + // Get Creatively + PlayerSet set = this.markerApi.getPlayerSet(setId); + if (set == null) { + set = this.markerApi.createPlayerSet(setId, // id + true, // symmetric + playerIds, // players + false // persistent + ); + } + if (set == null) { + severe("Could not get/create the player set " + setId); + continue; + } + + // Set Content + set.setPlayers(playerIds); + } + } + + // Thread Safe / Asynchronous: Yes + private String getDescription(Faction faction) { + String ret = "
" + Conf.dynmapDescription + "
"; + + // Name + String name = faction.getTag(); + name = escapeHtml(ChatColor.stripColor(name)); + ret = ret.replace("%name%", name); + + // Description + String description = faction.getDescription(); + description = escapeHtml(ChatColor.stripColor(description)); + ret = ret.replace("%description%", description); + + // Money + + String money = "unavailable"; + if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) + money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); + ret = ret.replace("%money%", money); + + + // Players + Set playersList = faction.getFPlayers(); + String playersCount = String.valueOf(playersList.size()); + String players = getHtmlPlayerString(playersList); + + FPlayer playersLeaderObject = faction.getFPlayerAdmin(); + String playersLeader = getHtmlPlayerName(playersLeaderObject); + + ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); + String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); + String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); + + ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); + String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); + String playersModerators = getHtmlPlayerString(playersModeratorsList); + + + ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); + String playersNormalsCount = String.valueOf(playersNormalsList.size()); + String playersNormals = getHtmlPlayerString(playersNormalsList); + + ret = ret.replace("%players%", players); + ret = ret.replace("%players.count%", playersCount); + ret = ret.replace("%players.leader%", playersLeader); + ret = ret.replace("%players.admins%", playersCoAdmins); + ret = ret.replace("%players.admins.count%", playersCoAdminsCount); + ret = ret.replace("%players.moderators%", playersModerators); + ret = ret.replace("%players.moderators.count%", playersModeratorsCount); + ret = ret.replace("%players.normals%", playersNormals); + ret = ret.replace("%players.normals.count%", playersNormalsCount); + + return ret; + } + + // Thread Safe / Asynchronous: Yes + private boolean isVisible(Faction faction, String world) { + if (faction == null) { + return false; + } + final String factionId = faction.getId(); + if (factionId == null) { + return false; + } + final String factionName = faction.getTag(); + if (factionName == null) { + return false; + } + + Set visible = Conf.dynmapVisibleFactions; + Set hidden = Conf.dynmapHiddenFactions; + + if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { + return false; + } + + return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); + } + + // Thread Safe / Asynchronous: Yes + public DynmapStyle getStyle(Faction faction) { + DynmapStyle ret; + + ret = Conf.dynmapFactionStyles.get(faction.getId()); + if (ret != null) { + return ret; + } + + ret = Conf.dynmapFactionStyles.get(faction.getTag()); + if (ret != null) { + return ret; + } + + return Conf.dynmapDefaultStyle; + } + + // Find all contiguous blocks, set in target and clear in source + private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { + int cnt = 0; + ArrayDeque stack = new ArrayDeque<>(); + stack.push(new int[]{x, y}); + + while (!stack.isEmpty()) { + int[] nxt = stack.pop(); + x = nxt[0]; + y = nxt[1]; + if (source.getFlag(x, y)) { // Set in src + source.setFlag(x, y, false); // Clear source + destination.setFlag(x, y, true); // Set in destination + cnt++; + if (source.getFlag(x + 1, y)) { + stack.push(new int[]{x + 1, y}); + } + if (source.getFlag(x - 1, y)) { + stack.push(new int[]{x - 1, y}); + } + if (source.getFlag(x, y + 1)) { + stack.push(new int[]{x, y + 1}); + } + if (source.getFlag(x, y - 1)) { + stack.push(new int[]{x, y - 1}); + } + } + } + return cnt; + } + + enum Direction { + XPLUS, ZPLUS, XMINUS, ZMINUS + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java index 33e695b4..ec346d53 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java @@ -4,113 +4,113 @@ import org.dynmap.markers.AreaMarker; import org.dynmap.markers.MarkerSet; public class TempAreaMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String label; - public String world; - public double[] x; - public double[] z; - public String description; + public String label; + public String world; + public double[] x; + public double[] z; + public String description; - public int lineColor; - public double lineOpacity; - public int lineWeight; + public int lineColor; + public double lineOpacity; + public int lineWeight; - public int fillColor; - public double fillOpacity; + public int fillColor; + public double fillOpacity; - public boolean boost; + public boolean boost; - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - public static boolean equals(AreaMarker marker, double[] x, double[] z) { - int length = marker.getCornerCount(); + public static boolean equals(AreaMarker marker, double[] x, double[] z) { + int length = marker.getCornerCount(); - if (x.length != length) { - return false; - } - if (z.length != length) { - return false; - } + if (x.length != length) { + return false; + } + if (z.length != length) { + return false; + } - for (int i = 0; i < length; i++) { - if (marker.getCornerX(i) != x[i]) { - return false; - } - if (marker.getCornerZ(i) != z[i]) { - return false; - } - } + for (int i = 0; i < length; i++) { + if (marker.getCornerX(i) != x[i]) { + return false; + } + if (marker.getCornerZ(i) != z[i]) { + return false; + } + } - return true; - } + return true; + } - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - public AreaMarker create(MarkerSet markerset, String markerId) { - AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent - ); + public AreaMarker create(MarkerSet markerset, String markerId) { + AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent + ); - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - // Description - ret.setDescription(this.description); + // Description + ret.setDescription(this.description); - // Line Style - ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + // Line Style + ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - // Fill Style - ret.setFillStyle(this.fillOpacity, this.fillColor); + // Fill Style + ret.setFillStyle(this.fillOpacity, this.fillColor); - // Boost Flag - ret.setBoostFlag(this.boost); + // Boost Flag + ret.setBoostFlag(this.boost); - return ret; - } + return ret; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public void update(AreaMarker marker) { - // Corner Locations - if (!equals(marker, this.x, this.z)) { - marker.setCornerLocations(this.x, this.z); - } + public void update(AreaMarker marker) { + // Corner Locations + if (!equals(marker, this.x, this.z)) { + marker.setCornerLocations(this.x, this.z); + } - // Label - if (!marker.getLabel().equals(this.label)) { - marker.setLabel(this.label); - } + // Label + if (!marker.getLabel().equals(this.label)) { + marker.setLabel(this.label); + } - // Description - if (!marker.getDescription().equals(this.description)) { - marker.setDescription(this.description); - } + // Description + if (!marker.getDescription().equals(this.description)) { + marker.setDescription(this.description); + } - // Line Style - if (marker.getLineWeight() != this.lineWeight || - marker.getLineOpacity() != this.lineOpacity || - marker.getLineColor() != this.lineColor) { - marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - } + // Line Style + if (marker.getLineWeight() != this.lineWeight || + marker.getLineOpacity() != this.lineOpacity || + marker.getLineColor() != this.lineColor) { + marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + } - // Fill Style - if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { - marker.setFillStyle(this.fillOpacity, this.fillColor); - } - // Boost Flag - if (marker.getBoostFlag() != this.boost) { - marker.setBoostFlag(this.boost); - } - } + // Fill Style + if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { + marker.setFillStyle(this.fillOpacity, this.fillColor); + } + // Boost Flag + if (marker.getBoostFlag() != this.boost) { + marker.setBoostFlag(this.boost); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java index d977ae9f..b8eefdbe 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java @@ -7,68 +7,68 @@ import org.dynmap.markers.MarkerIcon; import org.dynmap.markers.MarkerSet; public class TempMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String label; - public String world; - public double x; - public double y; - public double z; - public String iconName; - public String description; + public String label; + public String world; + public double x; + public double y; + public double z; + public String iconName; + public String description; - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) { - MarkerIcon ret = markerApi.getMarkerIcon(name); - if (ret == null) { - ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER); - } - return ret; - } + public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) { + MarkerIcon ret = markerApi.getMarkerIcon(name); + if (ret == null) { + ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER); + } + return ret; + } - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { - Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent - ); + public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { + Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent + ); - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - ret.setDescription(this.description); + ret.setDescription(this.description); - return ret; - } + return ret; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public void update(MarkerAPI markerApi, Marker marker) { - if (!this.world.equals(marker.getWorld()) || this.x != marker.getX() || this.y != marker.getY() || this.z != marker.getZ()) { - marker.setLocation(this.world, this.x, this.y, this.z); - } + public void update(MarkerAPI markerApi, Marker marker) { + if (!this.world.equals(marker.getWorld()) || this.x != marker.getX() || this.y != marker.getY() || this.z != marker.getZ()) { + marker.setLocation(this.world, this.x, this.y, this.z); + } - if (!marker.getLabel().equals(this.label)) { - marker.setLabel(this.label); - } + if (!marker.getLabel().equals(this.label)) { + marker.setLabel(this.label); + } - MarkerIcon icon = getMarkerIcon(markerApi, this.iconName); - if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) { - marker.setMarkerIcon(icon); - } + MarkerIcon icon = getMarkerIcon(markerApi, this.iconName); + if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) { + marker.setMarkerIcon(icon); + } - if (!marker.getDescription().equals(this.description)) { - marker.setDescription(this.description); - } - } + if (!marker.getDescription().equals(this.description)) { + marker.setDescription(this.description); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java index 828a2f58..553bbde6 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java @@ -5,51 +5,51 @@ import org.dynmap.markers.MarkerSet; public class TempMarkerSet { - public String label; - public int minimumZoom; - public int priority; - public boolean hideByDefault; + public String label; + public int minimumZoom; + public int priority; + public boolean hideByDefault; - public MarkerSet create(MarkerAPI markerApi, String id) { - MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent") + public MarkerSet create(MarkerAPI markerApi, String id) { + MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent") - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - // Minimum Zoom - if (this.minimumZoom > 0) { - ret.setMinZoom(this.minimumZoom); - } + // Minimum Zoom + if (this.minimumZoom > 0) { + ret.setMinZoom(this.minimumZoom); + } - // Priority - ret.setLayerPriority(this.priority); + // Priority + ret.setLayerPriority(this.priority); - // Hide by Default - ret.setHideByDefault(this.hideByDefault); + // Hide by Default + ret.setHideByDefault(this.hideByDefault); - return ret; - } + return ret; + } - public void update(MarkerSet markerset) { - // Name - if (!markerset.getMarkerSetLabel().equals(this.label)) { - markerset.setMarkerSetLabel(this.label); - } + public void update(MarkerSet markerset) { + // Name + if (!markerset.getMarkerSetLabel().equals(this.label)) { + markerset.setMarkerSetLabel(this.label); + } - if (this.minimumZoom > 0) { - if (markerset.getMinZoom() != this.minimumZoom) { - markerset.setMinZoom(this.minimumZoom); - } - } + if (this.minimumZoom > 0) { + if (markerset.getMinZoom() != this.minimumZoom) { + markerset.setMinZoom(this.minimumZoom); + } + } - if (markerset.getLayerPriority() != this.priority) { - markerset.setLayerPriority(this.priority); - } + if (markerset.getLayerPriority() != this.priority) { + markerset.setLayerPriority(this.priority); + } - if (markerset.getHideByDefault() != this.hideByDefault) { - markerset.setHideByDefault(this.hideByDefault); - } - } + if (markerset.getHideByDefault() != this.hideByDefault) { + markerset.setHideByDefault(this.hideByDefault); + } + } } diff --git a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java index 93fc70ea..55e16938 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java @@ -10,32 +10,32 @@ import java.util.ListIterator; public class FDefaultSidebar extends FSidebarProvider { - @Override - public String getTitle(FPlayer fplayer) { - return replaceTags(fplayer, P.p.getConfig().getString("scoreboard.default-title", "{name}")); - } + @Override + public String getTitle(FPlayer fplayer) { + return replaceTags(fplayer, P.p.getConfig().getString("scoreboard.default-title", "{name}")); + } - @Override - public List getLines(FPlayer fplayer) { - if (fplayer.hasFaction()) { - return getOutput(fplayer, "scoreboard.default"); - } else if (P.p.getConfig().getBoolean("scoreboard.factionless-enabled", false)) { - return getOutput(fplayer, "scoreboard.factionless"); - } - return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled - } + @Override + public List getLines(FPlayer fplayer) { + if (fplayer.hasFaction()) { + return getOutput(fplayer, "scoreboard.default"); + } else if (P.p.getConfig().getBoolean("scoreboard.factionless-enabled", false)) { + return getOutput(fplayer, "scoreboard.factionless"); + } + return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled + } - public List getOutput(FPlayer fplayer, String list) { - List lines = P.p.getConfig().getStringList(list); + public List getOutput(FPlayer fplayer, String list) { + List lines = P.p.getConfig().getStringList(list); - if (lines == null || lines.isEmpty()) { - return new ArrayList<>(); - } + if (lines == null || lines.isEmpty()) { + return new ArrayList<>(); + } - ListIterator it = lines.listIterator(); - while (it.hasNext()) { - it.set(replaceTags(fplayer, it.next())); - } - return lines; - } + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + it.set(replaceTags(fplayer, it.next())); + } + return lines; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java index 5ca0dc0e..d3752728 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java @@ -9,25 +9,25 @@ import java.util.List; import java.util.ListIterator; public class FInfoSidebar extends FSidebarProvider { - private final Faction faction; + private final Faction faction; - public FInfoSidebar(Faction faction) { - this.faction = faction; - } + public FInfoSidebar(Faction faction) { + this.faction = faction; + } - @Override - public String getTitle(FPlayer fplayer) { - return faction.getRelationTo(fplayer).getColor() + faction.getTag(); - } + @Override + public String getTitle(FPlayer fplayer) { + return faction.getRelationTo(fplayer).getColor() + faction.getTag(); + } - @Override - public List getLines(FPlayer fplayer) { - List lines = P.p.getConfig().getStringList("scoreboard.finfo"); + @Override + public List getLines(FPlayer fplayer) { + List lines = P.p.getConfig().getStringList("scoreboard.finfo"); - ListIterator it = lines.listIterator(); - while (it.hasNext()) { - it.set(replaceTags(faction, fplayer, it.next())); - } - return lines; - } + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + it.set(replaceTags(faction, fplayer, it.next())); + } + return lines; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java index 68873c29..ca65fe11 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerChunkLocationExpression.java @@ -7,14 +7,13 @@ import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import com.massivecraft.factions.*; -import org.bukkit.Chunk; import org.bukkit.entity.Player; import org.bukkit.event.Event; public class PlayerChunkLocationExpression extends SimpleExpression { - static{ - Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE,"[the] faction chunk at %player%", "[the] %player%['s] chunk"); + static { + Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction chunk at %player%", "[the] %player%['s] chunk"); } Expression playerExpression; diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java index a0d99bc0..794e55f2 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java @@ -18,78 +18,78 @@ import org.bukkit.event.Event; public class PlayerFactionExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction"); - } + static { + Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return String.class; - } + @Override + public Class getReturnType() { + return String.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); + } - @Override - protected String[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected String[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new String[]{fPlayer.getFaction().getTag()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new String[]{fPlayer.getFaction().getTag()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { - return CollectionUtils.array(String.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { + return CollectionUtils.array(String.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case DELETE: - case RESET: - fPlayer.setFaction(Factions.getInstance().getWilderness(), false); - break; - case SET: - Faction faction = Factions.getInstance().getByTag((String) delta[0]); - if (faction == null) { - faction = Factions.getInstance().getWilderness(); - } - fPlayer.setFaction(faction, false); - break; - default: - } - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case DELETE: + case RESET: + fPlayer.setFaction(Factions.getInstance().getWilderness(), false); + break; + case SET: + Faction faction = Factions.getInstance().getByTag((String) delta[0]); + if (faction == null) { + faction = Factions.getInstance().getWilderness(); + } + fPlayer.setFaction(faction, false); + break; + default: + } + } } diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java index f4d2c4c2..928da2e5 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java @@ -16,80 +16,80 @@ import org.bukkit.event.Event; public class PlayerPowerExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power"); - } + static { + Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return Double.class; - } + @Override + public Class getReturnType() { + return Double.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Power with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Power with expression player" + playerExpression.toString(event, debug); + } - @Override - protected Double[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected Double[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new Double[]{fPlayer.getFaction().getPower()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new Double[]{fPlayer.getFaction().getPower()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) { - return CollectionUtils.array(Number.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) { + return CollectionUtils.array(Number.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case ADD: - fPlayer.alterPower(Double.valueOf((Long) delta[0])); - break; - case REMOVE: - fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1); - break; - case RESET: - fPlayer.alterPower(fPlayer.getPowerMax() * -1); - break; - default: - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case ADD: + fPlayer.alterPower(Double.valueOf((Long) delta[0])); + break; + case REMOVE: + fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1); + break; + case RESET: + fPlayer.alterPower(fPlayer.getPowerMax() * -1); + break; + default: + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java index 238c6134..13d96ade 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java @@ -16,77 +16,77 @@ import org.bukkit.event.Event; public class PlayerRoleExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role"); - } + static { + Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return String.class; - } + @Override + public Class getReturnType() { + return String.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); + } - @Override - protected String[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected String[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new String[]{fPlayer.getRole().toString()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new String[]{fPlayer.getRole().toString()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { - return CollectionUtils.array(String.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { + return CollectionUtils.array(String.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case DELETE: - case RESET: - fPlayer.setRole(Role.RECRUIT); - break; - case SET: - fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase())); - break; - default: - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case DELETE: + case RESET: + fPlayer.setRole(Role.RECRUIT); + break; + case SET: + fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase())); + break; + default: + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java b/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java index be7a1e06..fcc8efc7 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java @@ -3,42 +3,44 @@ package com.massivecraft.factions.zcore.fperms; import com.massivecraft.factions.P; public enum Access { - ALLOW("Allow"), - DENY("Deny"), - UNDEFINED("Undefined"); + ALLOW("Allow"), + DENY("Deny"), + UNDEFINED("Undefined"); - private final String name; + private final String name; - Access(String name) { - this.name = name; - } + Access(String name) { + this.name = name; + } - /** - * Case insensitive check for access. - * - * @param check - * @return - */ - public static Access fromString(String check) { - for (Access access : values()) - if (access.name().equalsIgnoreCase(check)) - return access; - return null; - } + /** + * Case insensitive check for access. + * + * @param check + * @return + */ + public static Access fromString(String check) { + for (Access access : values()) + if (access.name().equalsIgnoreCase(check)) + return access; + return null; + } - public String getName() { - return this.name.toLowerCase(); - } + public static Access booleanToAccess(boolean access) { + if (access) return Access.ALLOW; + else return Access.DENY; + } - @Override - public String toString() { - return name(); - } + public String getName() { + return this.name.toLowerCase(); + } - public String getColor() { return P.p.getConfig().getString("fperm-gui.action.Access-Colors." + this.name); } + @Override + public String toString() { + return name(); + } - public static Access booleanToAccess(boolean access) { - if (access) return Access.ALLOW; - else return Access.DENY; - } + public String getColor() { + return P.p.getConfig().getString("fperm-gui.action.Access-Colors." + this.name); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java b/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java index c405d786..5cd98f87 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java @@ -1,160 +1,157 @@ package com.massivecraft.factions.zcore.fperms; -import com.massivecraft.factions.util.XMaterial; -import javafx.scene.paint.Material; - public class DefaultPermissions { - public boolean ban; - public boolean build; - public boolean destroy; - public boolean frostwalk; - public boolean painbuild; - public boolean door; - public boolean button; - public boolean lever; - public boolean container; - public boolean invite; - public boolean kick; - public boolean items; - public boolean sethome; - public boolean territory; - public boolean access; - public boolean home; - public boolean disband; - public boolean promote; - public boolean setwarp; - public boolean warp; - public boolean fly; - public boolean vault; - public boolean tntbank; - public boolean tntfill; - public boolean withdraw; - public boolean chest; - public boolean check; - public boolean spawner; + public boolean ban; + public boolean build; + public boolean destroy; + public boolean frostwalk; + public boolean painbuild; + public boolean door; + public boolean button; + public boolean lever; + public boolean container; + public boolean invite; + public boolean kick; + public boolean items; + public boolean sethome; + public boolean territory; + public boolean access; + public boolean home; + public boolean disband; + public boolean promote; + public boolean setwarp; + public boolean warp; + public boolean fly; + public boolean vault; + public boolean tntbank; + public boolean tntfill; + public boolean withdraw; + public boolean chest; + public boolean check; + public boolean spawner; - public DefaultPermissions() { - } + public DefaultPermissions() { + } - public DefaultPermissions(boolean def) { - this.ban = def; - this.build = def; - this.destroy = def; - this.frostwalk = def; - this.painbuild = def; - this.door = def; - this.button = def; - this.lever = def; - this.container = def; - this.invite = def; - this.kick = def; - this.items = def; - this.sethome = def; - this.territory = def; - this.access = def; - this.home = def; - this.disband = def; - this.promote = def; - this.setwarp = def; - this.warp = def; - this.fly = def; - this.vault = def; - this.tntbank = def; - this.tntfill = def; - this.withdraw = def; - this.chest = def; - this.check = def; - this.spawner = def; - } + public DefaultPermissions(boolean def) { + this.ban = def; + this.build = def; + this.destroy = def; + this.frostwalk = def; + this.painbuild = def; + this.door = def; + this.button = def; + this.lever = def; + this.container = def; + this.invite = def; + this.kick = def; + this.items = def; + this.sethome = def; + this.territory = def; + this.access = def; + this.home = def; + this.disband = def; + this.promote = def; + this.setwarp = def; + this.warp = def; + this.fly = def; + this.vault = def; + this.tntbank = def; + this.tntfill = def; + this.withdraw = def; + this.chest = def; + this.check = def; + this.spawner = def; + } - public DefaultPermissions(boolean canBan, - boolean canBuild, - boolean canDestory, - boolean canFrostwalk, - boolean canPainbuild, - boolean canDoor, - boolean canButton, - boolean canLever, - boolean canContainer, - boolean canInvite, - boolean canKick, - boolean canItems, - boolean canSethome, - boolean canTerritory, - boolean canAccess, - boolean canHome, - boolean canDisband, - boolean canPromote, - boolean canSetwarp, - boolean canWarp, - boolean canFly, - boolean canVault, - boolean canTntbank, - boolean canTntfill, - boolean canWithdraw, - boolean canChest, - boolean canCheck, - boolean canSpawners) { - this.ban = canBan; - this.build = canBuild; - this.destroy = canDestory; - this.frostwalk = canFrostwalk; - this.painbuild = canPainbuild; - this.door = canDoor; - this.button = canButton; - this.lever = canLever; - this.container = canContainer; - this.invite = canInvite; - this.kick = canKick; - this.items = canItems; - this.sethome = canSethome; - this.territory = canTerritory; - this.access = canAccess; - this.home = canHome; - this.disband = canDisband; - this.promote = canPromote; - this.setwarp = canSetwarp; - this.warp = canWarp; - this.fly = canFly; - this.vault = canVault; - this.tntbank = canTntbank; - this.tntfill = canTntfill; - this.withdraw = canWithdraw; - this.chest = canChest; - this.check = canCheck; - this.spawner = canSpawners; - } + public DefaultPermissions(boolean canBan, + boolean canBuild, + boolean canDestory, + boolean canFrostwalk, + boolean canPainbuild, + boolean canDoor, + boolean canButton, + boolean canLever, + boolean canContainer, + boolean canInvite, + boolean canKick, + boolean canItems, + boolean canSethome, + boolean canTerritory, + boolean canAccess, + boolean canHome, + boolean canDisband, + boolean canPromote, + boolean canSetwarp, + boolean canWarp, + boolean canFly, + boolean canVault, + boolean canTntbank, + boolean canTntfill, + boolean canWithdraw, + boolean canChest, + boolean canCheck, + boolean canSpawners) { + this.ban = canBan; + this.build = canBuild; + this.destroy = canDestory; + this.frostwalk = canFrostwalk; + this.painbuild = canPainbuild; + this.door = canDoor; + this.button = canButton; + this.lever = canLever; + this.container = canContainer; + this.invite = canInvite; + this.kick = canKick; + this.items = canItems; + this.sethome = canSethome; + this.territory = canTerritory; + this.access = canAccess; + this.home = canHome; + this.disband = canDisband; + this.promote = canPromote; + this.setwarp = canSetwarp; + this.warp = canWarp; + this.fly = canFly; + this.vault = canVault; + this.tntbank = canTntbank; + this.tntfill = canTntfill; + this.withdraw = canWithdraw; + this.chest = canChest; + this.check = canCheck; + this.spawner = canSpawners; + } - @Deprecated - public boolean getbyName(String name) { - if (name == "ban") return this.ban; - else if (name == "build") return this.build; - else if (name == "destroy") return this.destroy; - else if (name == "frostwalk") return this.frostwalk; - else if (name == "painbuild") return this.painbuild; - else if (name == "door") return this.door; - else if (name == "button") return this.button; - else if (name == "lever") return this.lever; - else if (name == "home") return this.home; - else if (name == "container") return this.container; - else if (name == "invite") return this.invite; - else if (name == "kick") return this.kick; - else if (name == "items") return this.items; - else if (name == "sethome") return this.sethome; - else if (name == "territory") return this.territory; - else if (name == "access") return this.access; - else if (name == "disband") return this.disband; - else if (name == "promote") return this.promote; - else if (name == "setwarp") return this.setwarp; - else if (name == "warp") return this.warp; - else if (name == "fly") return this.fly; - else if (name == "vault") return this.vault; - else if (name == "tntbank") return this.tntbank; - else if (name == "tntfill") return this.tntfill; - else if (name == "withdraw") return this.withdraw; - else if (name == "chest") return this.chest; - else if(name == "check") return this.check; - else if (name == "spawner") return this.spawner; - else return false; - } + @Deprecated + public boolean getbyName(String name) { + if (name == "ban") return this.ban; + else if (name == "build") return this.build; + else if (name == "destroy") return this.destroy; + else if (name == "frostwalk") return this.frostwalk; + else if (name == "painbuild") return this.painbuild; + else if (name == "door") return this.door; + else if (name == "button") return this.button; + else if (name == "lever") return this.lever; + else if (name == "home") return this.home; + else if (name == "container") return this.container; + else if (name == "invite") return this.invite; + else if (name == "kick") return this.kick; + else if (name == "items") return this.items; + else if (name == "sethome") return this.sethome; + else if (name == "territory") return this.territory; + else if (name == "access") return this.access; + else if (name == "disband") return this.disband; + else if (name == "promote") return this.promote; + else if (name == "setwarp") return this.setwarp; + else if (name == "warp") return this.warp; + else if (name == "fly") return this.fly; + else if (name == "vault") return this.vault; + else if (name == "tntbank") return this.tntbank; + else if (name == "tntfill") return this.tntfill; + else if (name == "withdraw") return this.withdraw; + else if (name == "chest") return this.chest; + else if (name == "check") return this.check; + else if (name == "spawner") return this.spawner; + else return false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java b/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java index 3412581b..3441f9d3 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java @@ -4,10 +4,10 @@ import org.bukkit.inventory.ItemStack; public interface Permissable { - ItemStack buildItem(); + ItemStack buildItem(); - String replacePlaceholders(String string); + String replacePlaceholders(String string); - String name(); + String name(); } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java b/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java index dfd3dd78..eb5f60cb 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java @@ -13,103 +13,105 @@ import java.util.List; import java.util.Map; public enum PermissableAction { - BAN("ban"), - BUILD("build"), - DESTROY("destroy"), - FROST_WALK("frostwalk"), - PAIN_BUILD("painbuild"), - DOOR("door"), - BUTTON("button"), - LEVER("lever"), - CONTAINER("container"), - INVITE("invite"), - KICK("kick"), - ITEM("items"), // generic for most items - SETHOME("sethome"), - TERRITORY("territory"), - ACCESS("access"), - HOME("home"), - DISBAND("disband"), - PROMOTE("promote"), - SETWARP("setwarp"), - WARP("warp"), - FLY("fly"), - VAULT("vault"), - TNTBANK("tntbank"), - TNTFILL("tntfill"), - WITHDRAW("withdraw"), - CHEST("chest"), - CHECK("check"), - SPAWNER("spawner"); + BAN("ban"), + BUILD("build"), + DESTROY("destroy"), + FROST_WALK("frostwalk"), + PAIN_BUILD("painbuild"), + DOOR("door"), + BUTTON("button"), + LEVER("lever"), + CONTAINER("container"), + INVITE("invite"), + KICK("kick"), + ITEM("items"), // generic for most items + SETHOME("sethome"), + TERRITORY("territory"), + ACCESS("access"), + HOME("home"), + DISBAND("disband"), + PROMOTE("promote"), + SETWARP("setwarp"), + WARP("warp"), + FLY("fly"), + VAULT("vault"), + TNTBANK("tntbank"), + TNTFILL("tntfill"), + WITHDRAW("withdraw"), + CHEST("chest"), + CHECK("check"), + SPAWNER("spawner"); - private String name; + private String name; - PermissableAction(String name) { - this.name = name; - } + PermissableAction(String name) { + this.name = name; + } - /** - * Case insensitive check for action. - * - * @param check - * @return - action - */ - public static PermissableAction fromString(String check) { - for (PermissableAction permissableAction : values()) { - if (permissableAction.name().equalsIgnoreCase(check)) { - return permissableAction; - } - } + /** + * Case insensitive check for action. + * + * @param check + * @return - action + */ + public static PermissableAction fromString(String check) { + for (PermissableAction permissableAction : values()) { + if (permissableAction.name().equalsIgnoreCase(check)) { + return permissableAction; + } + } - return null; - } + return null; + } - public int getSlot() { return P.p.getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase()); } + public static Map fromDefaults(DefaultPermissions defaultPermissions) { + Map defaultMap = new HashMap<>(); + for (PermissableAction permissableAction : PermissableAction.values()) { + defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY); + } + return defaultMap; + } - public static Map fromDefaults(DefaultPermissions defaultPermissions) { - Map defaultMap = new HashMap<>(); - for (PermissableAction permissableAction : PermissableAction.values()) { - defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY); - } - return defaultMap; - } + public static PermissableAction fromSlot(int slot) { + for (PermissableAction action : PermissableAction.values()) { + if (action.getSlot() == slot) return action; + } + return null; + } - /** - * Get the friendly name of this action. Used for editing in commands. - * - * @return friendly name of the action as a String. - */ - public String getName() { - return this.name; - } + public int getSlot() { + return P.p.getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase()); + } - @Override - public String toString() { - return name; - } + /** + * Get the friendly name of this action. Used for editing in commands. + * + * @return friendly name of the action as a String. + */ + public String getName() { + return this.name; + } - public ItemStack buildAsset(FPlayer fme, Permissable perm) { - ConfigurationSection section = P.p.getConfig().getConfigurationSection("fperm-gui.action"); - ItemStack item = XMaterial.matchXMaterial(section.getString("Materials." + this.name)).parseItem(); - ItemMeta meta = item.getItemMeta(); + @Override + public String toString() { + return name; + } - meta.setDisplayName(P.p.color(section.getString("placeholder-item.name").replace("{action}", this.name))); - List lore = section.getStringList("placeholder-item.lore"); + public ItemStack buildAsset(FPlayer fme, Permissable perm) { + ConfigurationSection section = P.p.getConfig().getConfigurationSection("fperm-gui.action"); + ItemStack item = XMaterial.matchXMaterial(section.getString("Materials." + this.name)).parseItem(); + ItemMeta meta = item.getItemMeta(); - lore = P.p.replacePlaceholders(lore, - new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()), - new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName())); + meta.setDisplayName(P.p.color(section.getString("placeholder-item.name").replace("{action}", this.name))); + List lore = section.getStringList("placeholder-item.lore"); - meta.setLore(P.p.colorList(lore)); - item.setItemMeta(meta); - return item; - } + lore = P.p.replacePlaceholders(lore, + new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()), + new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName())); - public static PermissableAction fromSlot(int slot) { - for (PermissableAction action : PermissableAction.values()) { - if (action.getSlot() == slot) return action; - } - return null; - } + meta.setLore(P.p.colorList(lore)); + item.setItemMeta(meta); + return item; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java index f9740dc4..11ee10bf 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java @@ -18,62 +18,62 @@ import java.util.concurrent.ThreadLocalRandom; public class CropUpgrades implements Listener { - @EventHandler - public void onCropGrow(BlockGrowEvent e) { - FLocation floc = new FLocation(e.getBlock().getLocation()); - Faction factionAtLoc = Board.getInstance().getFactionAt(floc); + @EventHandler + public void onCropGrow(BlockGrowEvent e) { + FLocation floc = new FLocation(e.getBlock().getLocation()); + Faction factionAtLoc = Board.getInstance().getFactionAt(floc); - if (!factionAtLoc.isWilderness()) { - int level = factionAtLoc.getUpgrade(UpgradeType.CROP); - if (level != 0) { - int chance = -1; + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(UpgradeType.CROP); + if (level != 0) { + int chance = -1; - switch (level) { - case 1: - chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); - break; - case 2: - chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); - break; - case 3: - chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); - break; - } + switch (level) { + case 1: + chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); + break; + case 2: + chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); + break; + case 3: + chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); + break; + } - if (chance >= 0) { - int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1); - if (randomNum <= chance) - growCrop(e); - } - } - } - } + if (chance >= 0) { + int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1); + if (randomNum <= chance) + growCrop(e); + } + } + } + } - private void growCrop(BlockGrowEvent e) { + private void growCrop(BlockGrowEvent e) { - if (e.getBlock().getType().equals(XMaterial.WHEAT.parseMaterial())) { - e.setCancelled(true); - Crops c = new Crops(CropState.RIPE); - BlockState bs = e.getBlock().getState(); - bs.setData(c); - bs.update(); - } + if (e.getBlock().getType().equals(XMaterial.WHEAT.parseMaterial())) { + e.setCancelled(true); + Crops c = new Crops(CropState.RIPE); + BlockState bs = e.getBlock().getState(); + bs.setData(c); + bs.update(); + } - Block below = e.getBlock().getLocation().subtract(0, 1, 0).getBlock(); + Block below = e.getBlock().getLocation().subtract(0, 1, 0).getBlock(); - if (below.getType() == XMaterial.SUGAR_CANE.parseMaterial()) { - Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); + if (below.getType() == XMaterial.SUGAR_CANE.parseMaterial()) { + Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); - if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { - above.setType(XMaterial.SUGAR_CANE.parseMaterial()); - } + if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { + above.setType(XMaterial.SUGAR_CANE.parseMaterial()); + } - } else if (below.getType() == Material.CACTUS) { - Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); + } else if (below.getType() == Material.CACTUS) { + Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); - if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { - above.setType(Material.CACTUS); - } - } - } + if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { + above.setType(Material.CACTUS); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java index 1402acef..4006ff72 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java @@ -11,42 +11,42 @@ import org.bukkit.event.entity.EntityDeathEvent; public class EXPUpgrade implements Listener { - @EventHandler - public void onDeath(EntityDeathEvent e) { - Entity killer = e.getEntity().getKiller(); + @EventHandler + public void onDeath(EntityDeathEvent e) { + Entity killer = e.getEntity().getKiller(); - if (killer == null) - return; + if (killer == null) + return; - FLocation floc = new FLocation(e.getEntity().getLocation()); - Faction faction = Board.getInstance().getFactionAt(floc); + FLocation floc = new FLocation(e.getEntity().getLocation()); + Faction faction = Board.getInstance().getFactionAt(floc); - if (!faction.isWilderness()) { - int level = faction.getUpgrade(UpgradeType.EXP); - if (level != 0) { + if (!faction.isWilderness()) { + int level = faction.getUpgrade(UpgradeType.EXP); + if (level != 0) { - double multiplier = -1; + double multiplier = -1; - switch (level) { - case 1: - multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); - break; - case 2: - multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); - break; - case 3: - multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); - break; - } + switch (level) { + case 1: + multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); + break; + case 2: + multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); + break; + case 3: + multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); + break; + } - if (multiplier >= 0) - spawnMoreExp(e, multiplier); - } - } - } + if (multiplier >= 0) + spawnMoreExp(e, multiplier); + } + } + } - private void spawnMoreExp(EntityDeathEvent e, double multiplier) { - double newExp = e.getDroppedExp() * multiplier; - e.setDroppedExp((int) newExp); - } + private void spawnMoreExp(EntityDeathEvent e, double multiplier) { + double newExp = e.getDroppedExp() * multiplier; + e.setDroppedExp((int) newExp); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java index 3feeff11..8e496a86 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java @@ -173,13 +173,13 @@ public class FUpgradesGUI implements Listener { break; } } - } else if(e.getCurrentItem().equals(memberItem)){ + } else if (e.getCurrentItem().equals(memberItem)) { int memberLevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS) + 1; - if(!P.p.getConfig().isSet("fupgrades.MainMenu.Members.Cost.level-" + memberLevel)){ + if (!P.p.getConfig().isSet("fupgrades.MainMenu.Members.Cost.level-" + memberLevel)) { return; } int cost = P.p.getConfig().getInt("fupgrades.MainMenu.Members.Cost.level-" + memberLevel); - if(hasMoney(fme, cost)){ + if (hasMoney(fme, cost)) { fme.getFaction().setUpgrade(UpgradeType.MEMBERS, memberLevel); fme.getPlayer().closeInventory(); takeMoney(fme, cost); @@ -268,7 +268,6 @@ public class FUpgradesGUI implements Listener { } - Material cropMaterial = Material.getMaterial(P.p.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type")); int cropAmt = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); short cropData = Short.parseShort(P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java index 861cd936..3eb284c0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java @@ -10,32 +10,32 @@ import org.bukkit.event.entity.SpawnerSpawnEvent; public class SpawnerUpgrades implements Listener { - @EventHandler - public void onSpawn(SpawnerSpawnEvent e) { - FLocation floc = new FLocation(e.getLocation()); - Faction factionAtLoc = Board.getInstance().getFactionAt(floc); + @EventHandler + public void onSpawn(SpawnerSpawnEvent e) { + FLocation floc = new FLocation(e.getLocation()); + Faction factionAtLoc = Board.getInstance().getFactionAt(floc); - if (!factionAtLoc.isWilderness()) { - int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER); - if (level != 0) { - switch (level) { - case 1: - lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); - break; - case 2: - lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); - break; - case 3: - lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); - break; - } - } - } - } + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER); + if (level != 0) { + switch (level) { + case 1: + lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); + break; + case 2: + lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); + break; + case 3: + lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); + break; + } + } + } + } - private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) { - int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier); - e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby); - } + private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) { + int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier); + e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java index 6fcbec3f..fbecc44e 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/UpgradeType.java @@ -2,16 +2,16 @@ package com.massivecraft.factions.zcore.fupgrades; public enum UpgradeType { - CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"), POWER("Power"), REDSTONE("Redstone"), MEMBERS("Members"); + CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"), POWER("Power"), REDSTONE("Redstone"), MEMBERS("Members"); - private String id; + private String id; - UpgradeType(String id) { - this.id = id; - } + UpgradeType(String id) { + this.id = id; + } - @Override - public String toString() { - return this.id; - } + @Override + public String toString() { + return this.id; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java index 70d4a387..8cec2e41 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java @@ -7,191 +7,191 @@ import java.util.Set; public class NBTCompound { - private String compundName; - private NBTCompound parent; + private String compundName; + private NBTCompound parent; - protected NBTCompound() { - } + protected NBTCompound() { + } - protected NBTCompound(NBTCompound owner, String name) { - this.compundName = name; - this.parent = owner; - } + protected NBTCompound(NBTCompound owner, String name) { + this.compundName = name; + this.parent = owner; + } - public String getName() { - return compundName; - } + public String getName() { + return compundName; + } - protected Object getCompound() { - return parent.getCompound(); - } + protected Object getCompound() { + return parent.getCompound(); + } - protected void setCompound(Object compound) { - parent.setCompound(compound); - } + protected void setCompound(Object compound) { + parent.setCompound(compound); + } - public NBTCompound getParent() { - return parent; - } + public NBTCompound getParent() { + return parent; + } - public void mergeCompound(NBTCompound comp) { - NBTReflectionUtil.addOtherNBTCompound(this, comp); - } + public void mergeCompound(NBTCompound comp) { + NBTReflectionUtil.addOtherNBTCompound(this, comp); + } - public void setString(String key, String value) { - NBTReflectionUtil.setString(this, key, value); - } + public void setString(String key, String value) { + NBTReflectionUtil.setString(this, key, value); + } - public String getString(String key) { - return NBTReflectionUtil.getString(this, key); - } + public String getString(String key) { + return NBTReflectionUtil.getString(this, key); + } - protected String getContent(String key) { - return NBTReflectionUtil.getContent(this, key); - } + protected String getContent(String key) { + return NBTReflectionUtil.getContent(this, key); + } - public void setInteger(String key, Integer value) { - NBTReflectionUtil.setInt(this, key, value); - } + public void setInteger(String key, Integer value) { + NBTReflectionUtil.setInt(this, key, value); + } - public Integer getInteger(String key) { - return NBTReflectionUtil.getInt(this, key); - } + public Integer getInteger(String key) { + return NBTReflectionUtil.getInt(this, key); + } - public void setDouble(String key, Double value) { - NBTReflectionUtil.setDouble(this, key, value); - } + public void setDouble(String key, Double value) { + NBTReflectionUtil.setDouble(this, key, value); + } - public Double getDouble(String key) { - return NBTReflectionUtil.getDouble(this, key); - } + public Double getDouble(String key) { + return NBTReflectionUtil.getDouble(this, key); + } - public void setByte(String key, Byte value) { - NBTReflectionUtil.setByte(this, key, value); - } + public void setByte(String key, Byte value) { + NBTReflectionUtil.setByte(this, key, value); + } - public Byte getByte(String key) { - return NBTReflectionUtil.getByte(this, key); - } + public Byte getByte(String key) { + return NBTReflectionUtil.getByte(this, key); + } - public void setShort(String key, Short value) { - NBTReflectionUtil.setShort(this, key, value); - } + public void setShort(String key, Short value) { + NBTReflectionUtil.setShort(this, key, value); + } - public Short getShort(String key) { - return NBTReflectionUtil.getShort(this, key); - } + public Short getShort(String key) { + return NBTReflectionUtil.getShort(this, key); + } - public void setLong(String key, Long value) { - NBTReflectionUtil.setLong(this, key, value); - } + public void setLong(String key, Long value) { + NBTReflectionUtil.setLong(this, key, value); + } - public Long getLong(String key) { - return NBTReflectionUtil.getLong(this, key); - } + public Long getLong(String key) { + return NBTReflectionUtil.getLong(this, key); + } - public void setFloat(String key, Float value) { - NBTReflectionUtil.setFloat(this, key, value); - } + public void setFloat(String key, Float value) { + NBTReflectionUtil.setFloat(this, key, value); + } - public Float getFloat(String key) { - return NBTReflectionUtil.getFloat(this, key); - } + public Float getFloat(String key) { + return NBTReflectionUtil.getFloat(this, key); + } - public void setByteArray(String key, byte[] value) { - NBTReflectionUtil.setByteArray(this, key, value); - } + public void setByteArray(String key, byte[] value) { + NBTReflectionUtil.setByteArray(this, key, value); + } - public byte[] getByteArray(String key) { - return NBTReflectionUtil.getByteArray(this, key); - } + public byte[] getByteArray(String key) { + return NBTReflectionUtil.getByteArray(this, key); + } - public void setIntArray(String key, int[] value) { - NBTReflectionUtil.setIntArray(this, key, value); - } + public void setIntArray(String key, int[] value) { + NBTReflectionUtil.setIntArray(this, key, value); + } - public int[] getIntArray(String key) { - return NBTReflectionUtil.getIntArray(this, key); - } + public int[] getIntArray(String key) { + return NBTReflectionUtil.getIntArray(this, key); + } - public void setBoolean(String key, Boolean value) { - NBTReflectionUtil.setBoolean(this, key, value); - } + public void setBoolean(String key, Boolean value) { + NBTReflectionUtil.setBoolean(this, key, value); + } - protected void set(String key, Object val) { - NBTReflectionUtil.set(this, key, val); - } + protected void set(String key, Object val) { + NBTReflectionUtil.set(this, key, val); + } - public Boolean getBoolean(String key) { - return NBTReflectionUtil.getBoolean(this, key); - } + public Boolean getBoolean(String key) { + return NBTReflectionUtil.getBoolean(this, key); + } - public void setObject(String key, Object value) { - NBTReflectionUtil.setObject(this, key, value); - } + public void setObject(String key, Object value) { + NBTReflectionUtil.setObject(this, key, value); + } - public T getObject(String key, Class type) { - return NBTReflectionUtil.getObject(this, key, type); - } + public T getObject(String key, Class type) { + return NBTReflectionUtil.getObject(this, key, type); + } - public Boolean hasKey(String key) { - return NBTReflectionUtil.hasKey(this, key); - } + public Boolean hasKey(String key) { + return NBTReflectionUtil.hasKey(this, key); + } - public void removeKey(String key) { - NBTReflectionUtil.remove(this, key); - } + public void removeKey(String key) { + NBTReflectionUtil.remove(this, key); + } - public Set getKeys() { - return NBTReflectionUtil.getKeys(this); - } + public Set getKeys() { + return NBTReflectionUtil.getKeys(this); + } - public NBTCompound addCompound(String name) { - NBTReflectionUtil.addNBTTagCompound(this, name); - return getCompound(name); - } + public NBTCompound addCompound(String name) { + NBTReflectionUtil.addNBTTagCompound(this, name); + return getCompound(name); + } - public NBTCompound getCompound(String name) { - NBTCompound next = new NBTCompound(this, name); - if (NBTReflectionUtil.valideCompound(next)) return next; - return null; - } + public NBTCompound getCompound(String name) { + NBTCompound next = new NBTCompound(this, name); + if (NBTReflectionUtil.valideCompound(next)) return next; + return null; + } - public NBTList getList(String name, NBTType type) { - return NBTReflectionUtil.getList(this, name, type); - } + public NBTList getList(String name, NBTType type) { + return NBTReflectionUtil.getList(this, name, type); + } - public NBTType getType(String name) { - if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) - return NBTType.NBTTagEnd; - return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); - } + public NBTType getType(String name) { + if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) + return NBTType.NBTTagEnd; + return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); + } - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - for (String key : getKeys()) { - result.append(toString(key)); - } - return result.toString(); - } + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (String key : getKeys()) { + result.append(toString(key)); + } + return result.toString(); + } - public String toString(String key) { - StringBuilder result = new StringBuilder(); - NBTCompound compound = this; - while (compound.getParent() != null) { - result.append(" "); - compound = compound.getParent(); - } - if (this.getType(key) == NBTType.NBTTagCompound) { - return this.getCompound(key).toString(); - } else { - return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); - } - } + public String toString(String key) { + StringBuilder result = new StringBuilder(); + NBTCompound compound = this; + while (compound.getParent() != null) { + result.append(" "); + compound = compound.getParent(); + } + if (this.getType(key) == NBTType.NBTTagCompound) { + return this.getCompound(key).toString(); + } else { + return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); + } + } - public String asNBTString() { - return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); - } + public String asNBTString() { + return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java index 6d79ad01..4652dbc4 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java @@ -2,31 +2,31 @@ package com.massivecraft.factions.zcore.nbtapi; public class NBTContainer extends NBTCompound { - private Object nbt; + private Object nbt; - public NBTContainer() { - this(NBTReflectionUtil.getNewNBTTag()); - } + public NBTContainer() { + this(NBTReflectionUtil.getNewNBTTag()); + } - protected NBTContainer(Object nbt) { - this.nbt = nbt; - } + protected NBTContainer(Object nbt) { + this.nbt = nbt; + } - public NBTContainer(String nbtString) throws IllegalArgumentException { - try { - nbt = NBTReflectionUtil.parseNBT(nbtString); - } catch (Exception ex) { - ex.printStackTrace(); - throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); - } - } + public NBTContainer(String nbtString) throws IllegalArgumentException { + try { + nbt = NBTReflectionUtil.parseNBT(nbtString); + } catch (Exception ex) { + ex.printStackTrace(); + throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); + } + } - protected Object getCompound() { - return nbt; - } + protected Object getCompound() { + return nbt; + } - protected void setCompound(Object tag) { - nbt = tag; - } + protected void setCompound(Object tag) { + nbt = tag; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java index 4176dfdc..2417393c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java @@ -4,18 +4,18 @@ import org.bukkit.entity.Entity; public class NBTEntity extends NBTCompound { - private final Entity ent; + private final Entity ent; - public NBTEntity(Entity entity) { - ent = entity; - } + public NBTEntity(Entity entity) { + ent = entity; + } - protected Object getCompound() { - return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); - } + protected Object getCompound() { + return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); + } - protected void setCompound(Object compound) { - NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); - } + protected void setCompound(Object compound) { + NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java index 26da8dc0..20ecd57f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java @@ -7,39 +7,39 @@ import java.io.IOException; public class NBTFile extends NBTCompound { - private final File file; - private Object nbt; + private final File file; + private Object nbt; - public NBTFile(File file) throws IOException { - this.file = file; - if (file.exists()) { - FileInputStream inputsteam = new FileInputStream(file); - nbt = NBTReflectionUtil.readNBTFile(inputsteam); - } else { - nbt = NBTReflectionUtil.getNewNBTTag(); - save(); - } - } + public NBTFile(File file) throws IOException { + this.file = file; + if (file.exists()) { + FileInputStream inputsteam = new FileInputStream(file); + nbt = NBTReflectionUtil.readNBTFile(inputsteam); + } else { + nbt = NBTReflectionUtil.getNewNBTTag(); + save(); + } + } - public void save() throws IOException { - if (!file.exists()) { - file.getParentFile().mkdirs(); - file.createNewFile(); - } - FileOutputStream outStream = new FileOutputStream(file); - NBTReflectionUtil.saveNBTFile(nbt, outStream); - } + public void save() throws IOException { + if (!file.exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + FileOutputStream outStream = new FileOutputStream(file); + NBTReflectionUtil.saveNBTFile(nbt, outStream); + } - public File getFile() { - return file; - } + public File getFile() { + return file; + } - protected Object getCompound() { - return nbt; - } + protected Object getCompound() { + return nbt; + } - protected void setCompound(Object compound) { - nbt = compound; - } + protected void setCompound(Object compound) { + nbt = compound; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java index 86d49245..1bd3528c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java @@ -4,34 +4,34 @@ import org.bukkit.inventory.ItemStack; public class NBTItem extends NBTCompound { - private ItemStack bukkitItem; + private ItemStack bukkitItem; - public NBTItem(ItemStack item) { - bukkitItem = item.clone(); - } + public NBTItem(ItemStack item) { + bukkitItem = item.clone(); + } - public static NBTContainer convertItemtoNBT(ItemStack item) { - return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); - } + public static NBTContainer convertItemtoNBT(ItemStack item) { + return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); + } - public static ItemStack convertNBTtoItem(NBTCompound comp) { - return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); - } + public static ItemStack convertNBTtoItem(NBTCompound comp) { + return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); + } - protected Object getCompound() { - return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); - } + protected Object getCompound() { + return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); + } - protected void setCompound(Object compound) { - bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); - } + protected void setCompound(Object compound) { + bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); + } - public ItemStack getItem() { - return bukkitItem; - } + public ItemStack getItem() { + return bukkitItem; + } - protected void setItem(ItemStack item) { - bukkitItem = item; - } + protected void setItem(ItemStack item) { + bukkitItem = item; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java index 91726778..a3d5a985 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java @@ -6,120 +6,120 @@ import java.lang.reflect.Method; public class NBTList { - private String listName; - private NBTCompound parent; - private NBTType type; - private Object listObject; + private String listName; + private NBTCompound parent; + private NBTType type; + private Object listObject; - protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { - parent = owner; - listName = name; - this.type = type; - this.listObject = list; - if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { - System.err.println("List types != String/Compound are currently not implemented!"); - } - } + protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { + parent = owner; + listName = name; + this.type = type; + this.listObject = list; + if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { + System.err.println("List types != String/Compound are currently not implemented!"); + } + } - protected void save() { - parent.set(listName, listObject); - } + protected void save() { + parent.set(listName, listObject); + } - public NBTListCompound addCompound() { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); - method.invoke(listObject, compound); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public NBTListCompound addCompound() { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); + Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); + method.invoke(listObject, compound); + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public NBTListCompound getCompound(int id) { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("get", int.class); - Object compound = method.invoke(listObject, id); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public NBTListCompound getCompound(int id) { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("get", int.class); + Object compound = method.invoke(listObject, id); + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public String getString(int i) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("getString", int.class); - return (String) method.invoke(listObject, i); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public String getString(int i) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("getString", int.class); + return (String) method.invoke(listObject, i); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public void addString(String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void addString(String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); + method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void setString(int i, String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setString(int i, String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); + method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void remove(int i) { - try { - Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); - method.invoke(listObject, i); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void remove(int i) { + try { + Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); + method.invoke(listObject, i); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public int size() { - try { - Method method = listObject.getClass().getMethod("size"); - return (int) method.invoke(listObject); - } catch (Exception ex) { - ex.printStackTrace(); - } - return -1; - } + public int size() { + try { + Method method = listObject.getClass().getMethod("size"); + return (int) method.invoke(listObject); + } catch (Exception ex) { + ex.printStackTrace(); + } + return -1; + } - public NBTType getType() { - return type; - } + public NBTType getType() { + return type; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java index 59a1ce5f..e3d92716 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java @@ -5,98 +5,98 @@ import java.util.Set; public class NBTListCompound { - private NBTList owner; - private Object compound; + private NBTList owner; + private Object compound; - protected NBTListCompound(NBTList parent, Object obj) { - owner = parent; - compound = obj; - } + protected NBTListCompound(NBTList parent, Object obj) { + owner = parent; + compound = obj; + } - public void setString(String key, String value) { - if (value == null) { - remove(key); - return; - } - try { - compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setString(String key, String value) { + if (value == null) { + remove(key); + return; + } + try { + compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void setInteger(String key, int value) { - try { - compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setInteger(String key, int value) { + try { + compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public int getInteger(String value) { - try { - return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } + public int getInteger(String value) { + try { + return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } - public void setDouble(String key, double value) { - try { - compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setDouble(String key, double value) { + try { + compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public double getDouble(String key) { - try { - return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } + public double getDouble(String key) { + try { + return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } - public String getString(String key) { - try { - return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return ""; - } + public String getString(String key) { + try { + return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } - public boolean hasKey(String key) { - try { - return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } + public boolean hasKey(String key) { + try { + return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } - @SuppressWarnings("unchecked") - public Set getKeys() { - try { - return (Set) compound.getClass().getMethod("c").invoke(compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return new HashSet<>(); - } + @SuppressWarnings("unchecked") + public Set getKeys() { + try { + return (Set) compound.getClass().getMethod("c").invoke(compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return new HashSet<>(); + } - public void remove(String key) { - try { - compound.getClass().getMethod("remove", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void remove(String key) { + try { + compound.getClass().getMethod("remove", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java index 5df3308e..a35684ef 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java @@ -19,904 +19,904 @@ import java.util.Stack; // TODO: finish codestyle cleanup -sgdc3 public class NBTReflectionUtil { - private static final String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - - private static Class getCraftItemStack() { - - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - private static Class getCraftEntity() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTBase() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTBase"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTTagString() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagString"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNMSItemStack() { - try { - return Class.forName("net.minecraft.server." + version + ".ItemStack"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTTagCompound() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTCompressedStreamTools() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getMojangsonParser() { - try { - return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getTileEntity() { - try { - return Class.forName("net.minecraft.server." + version + ".TileEntity"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getCraftWorld() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - public static Object getNewNBTTag() { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - return c.newInstance(); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - private static Object getNewBlockPosition(int x, int y, int z) { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); - return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - public static Object setNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method = NMSItem.getClass().getMethod("setTag", NBTTag.getClass()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getNMSItemStack(ItemStack item) { - Class clazz = getCraftItemStack(); - - try { - Method method = clazz.getMethod("asNMSCopy", ItemStack.class); - return method.invoke(clazz, item); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getNMSEntity(Entity entity) { - Class clazz = getCraftEntity(); - - try { - Method method = clazz.getMethod("getHandle"); - return method.invoke(getCraftEntity().cast(entity)); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object parseNBT(String json) { - Class cis = getMojangsonParser(); - - try { - Method method = cis.getMethod("parse", String.class); - return method.invoke(null, json); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object readNBTFile(FileInputStream stream) { - Class clazz = getNBTCompressedStreamTools(); - - try { - Method method = clazz.getMethod("a", InputStream.class); - return method.invoke(clazz, stream); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object saveNBTFile(Object nbt, FileOutputStream stream) { - Class clazz = getNBTCompressedStreamTools(); - - try { - Method method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); - return method.invoke(clazz, nbt, stream); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static ItemStack getBukkitItemStack(Object item) { - Class clazz = getCraftItemStack(); - - try { - Method method = clazz.getMethod("asCraftMirror", item.getClass()); - return (ItemStack) method.invoke(clazz, item); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getItemRootNBTTagCompound(Object nmsitem) { - Class clazz = nmsitem.getClass(); - - try { - Method method = clazz.getMethod("getTag"); - return method.invoke(nmsitem); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { - Class clazz = getNMSItemStack(); - try { - return clazz.getConstructor(getNBTTagCompound()).newInstance(gettoCompount(nbtcompound.getCompound(), nbtcompound)); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { - Class clazz = nmsitem.getClass(); - - try { - Method method = clazz.getMethod("save", getNBTTagCompound()); - Object answer = method.invoke(nmsitem, getNewNBTTag()); - return new NBTContainer(answer); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getEntityNBTTagCompound(Object nmsitem) { - Class c = nmsitem.getClass(); - - try { - Method method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); - Object nbt = getNBTTagCompound().newInstance(); - Object answer = method.invoke(nmsitem, nbt); - return answer != null ? answer : nbt; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object setEntityNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method; - method = NMSItem.getClass().getMethod(MethodNames.getEntityNbtSetterMethodName(), getNBTTagCompound()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getTileEntityNBTTagCompound(BlockState tile) { - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - Method method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); - Object tag = getNBTTagCompound().newInstance(); - Object answer = method.invoke(o, tag); - - return answer != null ? answer : tag; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - Method method = getTileEntity().getMethod("a", getNBTTagCompound()); - method.invoke(o, comp); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static Object getSubNBTTagCompound(Object compound, String name) { - Class c = compound.getClass(); - - try { - Method method = c.getMethod("getCompound", String.class); - return method.invoke(compound, name); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static void addNBTTagCompound(NBTCompound comp, String name) { - if (name == null) { - remove(comp, name); - return; - } - Object nbttag = comp.getCompound(); - if (nbttag == null) { - nbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(nbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, name, getNBTTagCompound().newInstance()); - comp.setCompound(nbttag); - return; - } catch (Exception ex) { - ex.printStackTrace(); - } - return; - } - - public static Boolean valideCompound(NBTCompound comp) { - Object root = comp.getCompound(); - if (root == null) { - root = getNewNBTTag(); - } - return gettoCompount(root, comp) != null; - } - - public static Object gettoCompount(Object nbttag, NBTCompound comp) { - Stack structure = new Stack<>(); - while (comp.getParent() != null) { - structure.add(comp.getName()); - comp = comp.getParent(); - } - while (!structure.isEmpty()) { - nbttag = getSubNBTTagCompound(nbttag, structure.pop()); - if (nbttag == null) { - return null; - } - } - return nbttag; - } - - public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("a", getNBTTagCompound()); - method.invoke(workingtag, nbtcompound.getCompound()); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setString(NBTCompound comp, String key, String text) { - if (text == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setString", String.class, String.class); - method.invoke(workingtag, key, text); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static String getString(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getString", String.class); - return (String) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static String getContent(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("get", String.class); - return method.invoke(workingtag, key).toString(); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setInt(NBTCompound comp, String key, Integer i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setInt", String.class, int.class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Integer getInt(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getInt", String.class); - return (Integer) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setByteArray(NBTCompound comp, String key, byte[] b) { - if (b == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setByteArray", String.class, byte[].class); - method.invoke(workingtag, key, b); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - return; - } - - public static byte[] getByteArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getByteArray", String.class); - return (byte[]) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setIntArray(NBTCompound comp, String key, int[] i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setIntArray", String.class, int[].class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static int[] getIntArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getIntArray", String.class); - return (int[]) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setFloat(NBTCompound comp, String key, Float f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setFloat", String.class, float.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Float getFloat(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getFloat", String.class); - return (Float) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setLong(NBTCompound comp, String key, Long f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setLong", String.class, long.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Long getLong(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getLong", String.class); - return (Long) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setShort(NBTCompound comp, String key, Short f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setShort", String.class, short.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Short getShort(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getShort", String.class); - return (Short) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setByte(NBTCompound comp, String key, Byte f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setByte", String.class, byte.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Byte getByte(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getByte", String.class); - return (Byte) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setDouble(NBTCompound comp, String key, Double d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setDouble", String.class, double.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Double getDouble(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getDouble", String.class); - return (Double) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static byte getType(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return 0; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); - return (byte) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } - - public static void setBoolean(NBTCompound comp, String key, Boolean d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setBoolean", String.class, boolean.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Boolean getBoolean(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getBoolean", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void set(NBTCompound comp, String key, Object val) { - if (val == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - new Throwable("InvalideCompound").printStackTrace(); - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - try { - Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, key, val); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static NBTList getList(NBTCompound comp, String key, NBTType type) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getList", String.class, int.class); - return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setObject(NBTCompound comp, String key, Object value) { - if (!MinecraftVersion.hasGsonSupport()) return; - try { - String json = GsonWrapper.getString(value); - setString(comp, key, json); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static T getObject(NBTCompound comp, String key, Class type) { - if (!MinecraftVersion.hasGsonSupport()) return null; - String json = getString(comp, key); - - return json != null ? GsonWrapper.deserializeJson(json, type) : null; - } - - public static void remove(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("remove", String.class); - method.invoke(workingtag, key); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Boolean hasKey(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("hasKey", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - @SuppressWarnings("unchecked") - public static Set getKeys(NBTCompound comp) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("c"); - return (Set) method.invoke(workingtag); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + private static final String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + + private static Class getCraftItemStack() { + + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + private static Class getCraftEntity() { + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTBase() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTBase"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTTagString() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTTagString"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNMSItemStack() { + try { + return Class.forName("net.minecraft.server." + version + ".ItemStack"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTTagCompound() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTCompressedStreamTools() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getMojangsonParser() { + try { + return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getTileEntity() { + try { + return Class.forName("net.minecraft.server." + version + ".TileEntity"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getCraftWorld() { + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + public static Object getNewNBTTag() { + String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + try { + Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); + return c.newInstance(); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + private static Object getNewBlockPosition(int x, int y, int z) { + String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + try { + Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); + return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + public static Object setNBTTag(Object NBTTag, Object NMSItem) { + try { + Method method = NMSItem.getClass().getMethod("setTag", NBTTag.getClass()); + method.invoke(NMSItem, NBTTag); + return NMSItem; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static Object getNMSItemStack(ItemStack item) { + Class clazz = getCraftItemStack(); + + try { + Method method = clazz.getMethod("asNMSCopy", ItemStack.class); + return method.invoke(clazz, item); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getNMSEntity(Entity entity) { + Class clazz = getCraftEntity(); + + try { + Method method = clazz.getMethod("getHandle"); + return method.invoke(getCraftEntity().cast(entity)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object parseNBT(String json) { + Class cis = getMojangsonParser(); + + try { + Method method = cis.getMethod("parse", String.class); + return method.invoke(null, json); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object readNBTFile(FileInputStream stream) { + Class clazz = getNBTCompressedStreamTools(); + + try { + Method method = clazz.getMethod("a", InputStream.class); + return method.invoke(clazz, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object saveNBTFile(Object nbt, FileOutputStream stream) { + Class clazz = getNBTCompressedStreamTools(); + + try { + Method method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); + return method.invoke(clazz, nbt, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static ItemStack getBukkitItemStack(Object item) { + Class clazz = getCraftItemStack(); + + try { + Method method = clazz.getMethod("asCraftMirror", item.getClass()); + return (ItemStack) method.invoke(clazz, item); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getItemRootNBTTagCompound(Object nmsitem) { + Class clazz = nmsitem.getClass(); + + try { + Method method = clazz.getMethod("getTag"); + return method.invoke(nmsitem); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { + Class clazz = getNMSItemStack(); + try { + return clazz.getConstructor(getNBTTagCompound()).newInstance(gettoCompount(nbtcompound.getCompound(), nbtcompound)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { + Class clazz = nmsitem.getClass(); + + try { + Method method = clazz.getMethod("save", getNBTTagCompound()); + Object answer = method.invoke(nmsitem, getNewNBTTag()); + return new NBTContainer(answer); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getEntityNBTTagCompound(Object nmsitem) { + Class c = nmsitem.getClass(); + + try { + Method method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); + Object nbt = getNBTTagCompound().newInstance(); + Object answer = method.invoke(nmsitem, nbt); + return answer != null ? answer : nbt; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object setEntityNBTTag(Object NBTTag, Object NMSItem) { + try { + Method method; + method = NMSItem.getClass().getMethod(MethodNames.getEntityNbtSetterMethodName(), getNBTTagCompound()); + method.invoke(NMSItem, NBTTag); + return NMSItem; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static Object getTileEntityNBTTagCompound(BlockState tile) { + try { + Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = getCraftWorld().cast(tile.getWorld()); + Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); + Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); + Method method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); + Object tag = getNBTTagCompound().newInstance(); + Object answer = method.invoke(o, tag); + + return answer != null ? answer : tag; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { + try { + Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = getCraftWorld().cast(tile.getWorld()); + Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); + Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); + Method method = getTileEntity().getMethod("a", getNBTTagCompound()); + method.invoke(o, comp); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Object getSubNBTTagCompound(Object compound, String name) { + Class c = compound.getClass(); + + try { + Method method = c.getMethod("getCompound", String.class); + return method.invoke(compound, name); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void addNBTTagCompound(NBTCompound comp, String name) { + if (name == null) { + remove(comp, name); + return; + } + Object nbttag = comp.getCompound(); + if (nbttag == null) { + nbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(nbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); + method.invoke(workingtag, name, getNBTTagCompound().newInstance()); + comp.setCompound(nbttag); + return; + } catch (Exception ex) { + ex.printStackTrace(); + } + return; + } + + public static Boolean valideCompound(NBTCompound comp) { + Object root = comp.getCompound(); + if (root == null) { + root = getNewNBTTag(); + } + return gettoCompount(root, comp) != null; + } + + public static Object gettoCompount(Object nbttag, NBTCompound comp) { + Stack structure = new Stack<>(); + while (comp.getParent() != null) { + structure.add(comp.getName()); + comp = comp.getParent(); + } + while (!structure.isEmpty()) { + nbttag = getSubNBTTagCompound(nbttag, structure.pop()); + if (nbttag == null) { + return null; + } + } + return nbttag; + } + + public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("a", getNBTTagCompound()); + method.invoke(workingtag, nbtcompound.getCompound()); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static void setString(NBTCompound comp, String key, String text) { + if (text == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setString", String.class, String.class); + method.invoke(workingtag, key, text); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static String getString(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getString", String.class); + return (String) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static String getContent(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("get", String.class); + return method.invoke(workingtag, key).toString(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setInt(NBTCompound comp, String key, Integer i) { + if (i == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setInt", String.class, int.class); + method.invoke(workingtag, key, i); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Integer getInt(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getInt", String.class); + return (Integer) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setByteArray(NBTCompound comp, String key, byte[] b) { + if (b == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setByteArray", String.class, byte[].class); + method.invoke(workingtag, key, b); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + return; + } + + public static byte[] getByteArray(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getByteArray", String.class); + return (byte[]) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setIntArray(NBTCompound comp, String key, int[] i) { + if (i == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setIntArray", String.class, int[].class); + method.invoke(workingtag, key, i); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static int[] getIntArray(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getIntArray", String.class); + return (int[]) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setFloat(NBTCompound comp, String key, Float f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setFloat", String.class, float.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Float getFloat(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getFloat", String.class); + return (Float) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setLong(NBTCompound comp, String key, Long f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setLong", String.class, long.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Long getLong(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getLong", String.class); + return (Long) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setShort(NBTCompound comp, String key, Short f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setShort", String.class, short.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Short getShort(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getShort", String.class); + return (Short) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setByte(NBTCompound comp, String key, Byte f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setByte", String.class, byte.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Byte getByte(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getByte", String.class); + return (Byte) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setDouble(NBTCompound comp, String key, Double d) { + if (d == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setDouble", String.class, double.class); + method.invoke(workingtag, key, d); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Double getDouble(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getDouble", String.class); + return (Double) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static byte getType(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return 0; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); + return (byte) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } + + public static void setBoolean(NBTCompound comp, String key, Boolean d) { + if (d == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setBoolean", String.class, boolean.class); + method.invoke(workingtag, key, d); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Boolean getBoolean(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getBoolean", String.class); + return (Boolean) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void set(NBTCompound comp, String key, Object val) { + if (val == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) { + new Throwable("InvalideCompound").printStackTrace(); + return; + } + Object workingtag = gettoCompount(rootnbttag, comp); + try { + Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); + method.invoke(workingtag, key, val); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static NBTList getList(NBTCompound comp, String key, NBTType type) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getList", String.class, int.class); + return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setObject(NBTCompound comp, String key, Object value) { + if (!MinecraftVersion.hasGsonSupport()) return; + try { + String json = GsonWrapper.getString(value); + setString(comp, key, json); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static T getObject(NBTCompound comp, String key, Class type) { + if (!MinecraftVersion.hasGsonSupport()) return null; + String json = getString(comp, key); + + return json != null ? GsonWrapper.deserializeJson(json, type) : null; + } + + public static void remove(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("remove", String.class); + method.invoke(workingtag, key); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Boolean hasKey(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("hasKey", String.class); + return (Boolean) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + @SuppressWarnings("unchecked") + public static Set getKeys(NBTCompound comp) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("c"); + return (Set) method.invoke(workingtag); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java index cfc56e06..dc78290e 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java @@ -4,18 +4,18 @@ import org.bukkit.block.BlockState; public class NBTTileEntity extends NBTCompound { - private final BlockState tile; + private final BlockState tile; - public NBTTileEntity(BlockState tile) { - this.tile = tile; - } + public NBTTileEntity(BlockState tile) { + this.tile = tile; + } - protected Object getCompound() { - return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); - } + protected Object getCompound() { + return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); + } - protected void setCompound(Object compound) { - NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); - } + protected void setCompound(Object compound) { + NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java index 37d87ec6..afa9d60a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java @@ -1,34 +1,34 @@ package com.massivecraft.factions.zcore.nbtapi; public enum NBTType { - NBTTagEnd(0), - NBTTagByte(1), - NBTTagShort(2), - NBTTagInt(3), - NBTTagLong(4), - NBTTagFloat(5), - NBTTagDouble(6), - NBTTagByteArray(7), - NBTTagIntArray(11), - NBTTagString(8), - NBTTagList(9), - NBTTagCompound(10); + NBTTagEnd(0), + NBTTagByte(1), + NBTTagShort(2), + NBTTagInt(3), + NBTTagLong(4), + NBTTagFloat(5), + NBTTagDouble(6), + NBTTagByteArray(7), + NBTTagIntArray(11), + NBTTagString(8), + NBTTagList(9), + NBTTagCompound(10); - private final int id; + private final int id; - NBTType(int i) { - id = i; - } + NBTType(int i) { + id = i; + } - public static NBTType valueOf(int id) { - for (NBTType t : values()) - if (t.getId() == id) - return t; - return NBTType.NBTTagEnd; - } + public static NBTType valueOf(int id) { + for (NBTType t : values()) + if (t.getId() == id) + return t; + return NBTType.NBTTagEnd; + } - public int getId() { - return id; - } + public int getId() { + return id; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java index 4a8eaf55..77492633 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java @@ -4,24 +4,24 @@ import com.google.gson.Gson; public class GsonWrapper { - private static final Gson gson = new Gson(); + private static final Gson gson = new Gson(); - public static String getString(Object obj) { - return gson.toJson(obj); - } + public static String getString(Object obj) { + return gson.toJson(obj); + } - public static T deserializeJson(String json, Class type) { - try { - if (json == null) { - return null; - } + public static T deserializeJson(String json, Class type) { + try { + if (json == null) { + return null; + } - T obj = gson.fromJson(json, type); - return type.cast(obj); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } + T obj = gson.fromJson(json, type); + return type.cast(obj); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java index f45ba7f6..126ad031 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java @@ -2,25 +2,25 @@ package com.massivecraft.factions.zcore.nbtapi.utils; public class MethodNames { - private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion(); + private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion(); - public static String getTileDataMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save"; - } + public static String getTileDataMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save"; + } - public static String getTypeMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d"; - } + public static String getTypeMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d"; + } - public static String getEntityNbtGetterMethodName() { - return "b"; - } + public static String getEntityNbtGetterMethodName() { + return "b"; + } - public static String getEntityNbtSetterMethodName() { - return "a"; - } + public static String getEntityNbtSetterMethodName() { + return "a"; + } - public static String getRemoveMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove"; - } + public static String getRemoveMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove"; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java index 3b3ea260..372610c1 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java @@ -3,58 +3,58 @@ package com.massivecraft.factions.zcore.nbtapi.utils; import org.bukkit.Bukkit; public enum MinecraftVersion { - Unknown(0), - MC1_7_R4(174), - MC1_8_R3(183), - MC1_9_R1(191), - MC1_9_R2(192), - MC1_10_R1(1101), - MC1_11_R1(1111), - MC1_12_R1(1121); + Unknown(0), + MC1_7_R4(174), + MC1_8_R3(183), + MC1_9_R1(191), + MC1_9_R2(192), + MC1_10_R1(1101), + MC1_11_R1(1111), + MC1_12_R1(1121); - private static MinecraftVersion version; - private static Boolean hasGsonSupport; + private static MinecraftVersion version; + private static Boolean hasGsonSupport; - private final int versionId; + private final int versionId; - MinecraftVersion(int versionId) { - this.versionId = versionId; - } + MinecraftVersion(int versionId) { + this.versionId = versionId; + } - public static MinecraftVersion getVersion() { - if (version == null) { - final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support"); + public static MinecraftVersion getVersion() { + if (version == null) { + final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support"); - try { - version = MinecraftVersion.valueOf(ver.replace("v", "MC")); - } catch (IllegalArgumentException ex) { - version = MinecraftVersion.Unknown; - } + try { + version = MinecraftVersion.valueOf(ver.replace("v", "MC")); + } catch (IllegalArgumentException ex) { + version = MinecraftVersion.Unknown; + } - if (version != Unknown) { - System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); - } else { - System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!"); - } - } - return version; - } + if (version != Unknown) { + System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); + } else { + System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!"); + } + } + return version; + } - public static boolean hasGsonSupport() { - if (hasGsonSupport == null) { - try { - System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); - hasGsonSupport = true; - } catch (Exception ex) { - hasGsonSupport = false; - } - } - return hasGsonSupport; - } + public static boolean hasGsonSupport() { + if (hasGsonSupport == null) { + try { + System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); + hasGsonSupport = true; + } catch (Exception ex) { + hasGsonSupport = false; + } + } + return hasGsonSupport; + } - public int getVersionId() { - return versionId; - } + public int getVersionId() { + return versionId; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java index 0ec657f1..a40662e7 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java @@ -19,367 +19,367 @@ import java.util.Map.Entry; public abstract class MemoryBoard extends Board { - public MemoryBoardMap flocationIds = new MemoryBoardMap(); + public MemoryBoardMap flocationIds = new MemoryBoardMap(); - //----------------------------------------------// - // Get and Set - //----------------------------------------------// - public String getIdAt(FLocation flocation) { - if (!flocationIds.containsKey(flocation)) { - return "0"; - } + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public String getIdAt(FLocation flocation) { + if (!flocationIds.containsKey(flocation)) { + return "0"; + } - return flocationIds.get(flocation); - } + return flocationIds.get(flocation); + } - public Faction getFactionAt(FLocation flocation) { - return Factions.getInstance().getFactionById(getIdAt(flocation)); - } + public Faction getFactionAt(FLocation flocation) { + return Factions.getInstance().getFactionById(getIdAt(flocation)); + } - public void setIdAt(String id, FLocation flocation) { - clearOwnershipAt(flocation); + public void setIdAt(String id, FLocation flocation) { + clearOwnershipAt(flocation); - if (id.equals("0")) { - removeAt(flocation); - } + if (id.equals("0")) { + removeAt(flocation); + } - flocationIds.put(flocation, id); - } + flocationIds.put(flocation, id); + } - public void setFactionAt(Faction faction, FLocation flocation) { - setIdAt(faction.getId(), flocation); - } + public void setFactionAt(Faction faction, FLocation flocation) { + setIdAt(faction.getId(), flocation); + } - public void removeAt(FLocation flocation) { - Faction faction = getFactionAt(flocation); - faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); - clearOwnershipAt(flocation); - flocationIds.remove(flocation); - } + public void removeAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); + clearOwnershipAt(flocation); + flocationIds.remove(flocation); + } - public Set getAllClaims(String factionId) { - Set locs = new HashSet<>(); - for (Entry entry : flocationIds.entrySet()) { - if (entry.getValue().equals(factionId)) { - locs.add(entry.getKey()); - } - } - return locs; - } + public Set getAllClaims(String factionId) { + Set locs = new HashSet<>(); + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId)) { + locs.add(entry.getKey()); + } + } + return locs; + } - public Set getAllClaims(Faction faction) { - return getAllClaims(faction.getId()); - } + public Set getAllClaims(Faction faction) { + return getAllClaims(faction.getId()); + } - // not to be confused with claims, ownership referring to further member-specific ownership of a claim - public void clearOwnershipAt(FLocation flocation) { - Faction faction = getFactionAt(flocation); - if (faction != null && faction.isNormal()) { - faction.clearClaimOwnership(flocation); - } - } + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public void clearOwnershipAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + if (faction != null && faction.isNormal()) { + faction.clearClaimOwnership(flocation); + } + } - public void unclaimAll(String factionId) { - Faction faction = Factions.getInstance().getFactionById(factionId); - if (faction != null && faction.isNormal()) { - faction.clearAllClaimOwnership(); - faction.clearWarps(); - } - clean(factionId); - } + public void unclaimAll(String factionId) { + Faction faction = Factions.getInstance().getFactionById(factionId); + if (faction != null && faction.isNormal()) { + faction.clearAllClaimOwnership(); + faction.clearWarps(); + } + clean(factionId); + } - public void unclaimAllInWorld(String factionId, World world) { - for (FLocation loc : getAllClaims(factionId)) { - if (loc.getWorldName().equals(world.getName())) { - removeAt(loc); - } - } - } + public void unclaimAllInWorld(String factionId, World world) { + for (FLocation loc : getAllClaims(factionId)) { + if (loc.getWorldName().equals(world.getName())) { + removeAt(loc); + } + } + } - public void clean(String factionId) { - flocationIds.removeFaction(factionId); - } + public void clean(String factionId) { + flocationIds.removeFaction(factionId); + } - // Is this coord NOT completely surrounded by coords claimed by the same faction? - // Simpler: Is there any nearby coord with a faction other than the faction here? - public boolean isBorderLocation(FLocation flocation) { - Faction faction = getFactionAt(flocation); - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); - } + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public boolean isBorderLocation(FLocation flocation) { + Faction faction = getFactionAt(flocation); + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); + } - // Is this coord connected to any coord claimed by the specified faction? - public boolean isConnectedLocation(FLocation flocation, Faction faction) { - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); - } + // Is this coord connected to any coord claimed by the specified faction? + public boolean isConnectedLocation(FLocation flocation, Faction faction) { + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); + } - /** - * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that - * requires a 'buffer' between factions. - * - * @param flocation - center location. - * @param faction - faction checking for. - * @param radius - chunk radius to check. - * @return true if another Faction is within the radius, otherwise false. - */ - public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { - for (int x = -radius; x <= radius; x++) { - for (int z = -radius; z <= radius; z++) { - if (x == 0 && z == 0) { - continue; - } + /** + * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that + * requires a 'buffer' between factions. + * + * @param flocation - center location. + * @param faction - faction checking for. + * @param radius - chunk radius to check. + * @return true if another Faction is within the radius, otherwise false. + */ + public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { + for (int x = -radius; x <= radius; x++) { + for (int z = -radius; z <= radius; z++) { + if (x == 0 && z == 0) { + continue; + } - FLocation relative = flocation.getRelative(x, z); - Faction other = getFactionAt(relative); + FLocation relative = flocation.getRelative(x, z); + Faction other = getFactionAt(relative); - if (other.isNormal() && other != faction) { - return true; - } - } - } - return false; - } + if (other.isNormal() && other != faction) { + return true; + } + } + } + return false; + } - public void clean() { - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (!Factions.getInstance().isValidFactionId(entry.getValue())) { - P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); - iter.remove(); - } - } - } + public void clean() { + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (!Factions.getInstance().isValidFactionId(entry.getValue())) { + P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); + iter.remove(); + } + } + } - //----------------------------------------------// - // Cleaner. Remove orphaned foreign keys - //----------------------------------------------// + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// - public int getFactionCoordCount(String factionId) { - return flocationIds.getOwnedLandCount(factionId); - } + public int getFactionCoordCount(String factionId) { + return flocationIds.getOwnedLandCount(factionId); + } - //----------------------------------------------// - // Coord count - //----------------------------------------------// + //----------------------------------------------// + // Coord count + //----------------------------------------------// - public int getFactionCoordCount(Faction faction) { - return getFactionCoordCount(faction.getId()); - } + public int getFactionCoordCount(Faction faction) { + return getFactionCoordCount(faction.getId()); + } - public int getFactionCoordCountInWorld(Faction faction, String worldName) { - String factionId = faction.getId(); - int ret = 0; - for (Entry entry : flocationIds.entrySet()) { - if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { - ret += 1; - } - } - return ret; - } + public int getFactionCoordCountInWorld(Faction faction, String worldName) { + String factionId = faction.getId(); + int ret = 0; + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { + ret += 1; + } + } + return ret; + } - /** - * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction - * of decreasing z - */ - public ArrayList getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { - Faction faction = fplayer.getFaction(); - ArrayList ret = new ArrayList<>(); - Faction factionLoc = getFactionAt(flocation); - ret.add(new FancyMessage(ChatColor.DARK_GRAY + P.p.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); - int buffer = P.p.getConfig().getInt("world-border.buffer", 0); + /** + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public ArrayList getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { + Faction faction = fplayer.getFaction(); + ArrayList ret = new ArrayList<>(); + Faction factionLoc = getFactionAt(flocation); + ret.add(new FancyMessage(ChatColor.DARK_GRAY + P.p.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); + int buffer = P.p.getConfig().getInt("world-border.buffer", 0); - // Get the compass - ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, P.p.txt.parse("")); + // Get the compass + ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, P.p.txt.parse("")); - int halfWidth = Conf.mapWidth / 2; - // Use player's value for height - int halfHeight = fplayer.getMapHeight() / 2; - FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); - int width = halfWidth * 2 + 1; - int height = halfHeight * 2 + 1; + int halfWidth = Conf.mapWidth / 2; + // Use player's value for height + int halfHeight = fplayer.getMapHeight() / 2; + FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); + int width = halfWidth * 2 + 1; + int height = halfHeight * 2 + 1; - if (Conf.showMapFactionKey) { - height--; - } + if (Conf.showMapFactionKey) { + height--; + } - Map fList = new HashMap<>(); - int chrIdx = 0; + Map fList = new HashMap<>(); + int chrIdx = 0; - // For each row - for (int dz = 0; dz < height; dz++) { - // Draw and add that row - FancyMessage row = new FancyMessage(""); + // For each row + for (int dz = 0; dz < height; dz++) { + // Draw and add that row + FancyMessage row = new FancyMessage(""); - if (dz < 3) { - row.then(asciiCompass.get(dz)); - } - for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { - if (dx == halfWidth && dz == halfHeight) { - row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString()); - } else { - FLocation flocationHere = topLeft.getRelative(dx, dz); - Faction factionHere = getFactionAt(flocationHere); - Relation relation = fplayer.getRelationTo(factionHere); - if (flocationHere.isOutsideWorldBorder(buffer)) { - row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); - } else if (factionHere.isWilderness()) { - row.then("-").color(Conf.colorWilderness); - // Lol someone didnt add the x and z making it claim the wrong position Can i copyright this xD - if (fplayer.getPlayer().hasPermission(Permission.CLAIMAT.node)) { - row.tooltip(TL.CLAIM_CLICK_TO_CLAIM.format(dx + topLeft.getX(), dz + topLeft.getZ())) - .command(String.format("/f claimat %s %d %d", flocation.getWorldName(), dx + topLeft.getX(), dz + topLeft.getZ())); - } - } else if (factionHere.isSafeZone()) { - row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer)); - } else if (factionHere.isWarZone()) { - row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer)); - } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || - (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || - (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) || - (Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) { - if (!fList.containsKey(factionHere.getTag())) { - fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]); - } - char tag = fList.get(factionHere.getTag()); + if (dz < 3) { + row.then(asciiCompass.get(dz)); + } + for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { + if (dx == halfWidth && dz == halfHeight) { + row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString()); + } else { + FLocation flocationHere = topLeft.getRelative(dx, dz); + Faction factionHere = getFactionAt(flocationHere); + Relation relation = fplayer.getRelationTo(factionHere); + if (flocationHere.isOutsideWorldBorder(buffer)) { + row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); + } else if (factionHere.isWilderness()) { + row.then("-").color(Conf.colorWilderness); + // Lol someone didnt add the x and z making it claim the wrong position Can i copyright this xD + if (fplayer.getPlayer().hasPermission(Permission.CLAIMAT.node)) { + row.tooltip(TL.CLAIM_CLICK_TO_CLAIM.format(dx + topLeft.getX(), dz + topLeft.getZ())) + .command(String.format("/f claimat %s %d %d", flocation.getWorldName(), dx + topLeft.getX(), dz + topLeft.getZ())); + } + } else if (factionHere.isSafeZone()) { + row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer)); + } else if (factionHere.isWarZone()) { + row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer)); + } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || + (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || + (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) || + (Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) { + if (!fList.containsKey(factionHere.getTag())) { + fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]); + } + char tag = fList.get(factionHere.getTag()); - //row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer)); - //changed out with a performance friendly one line tooltip :D - row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer)); - } else { - row.then("-").color(ChatColor.GRAY); - } - } - } - ret.add(row); - } + //row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer)); + //changed out with a performance friendly one line tooltip :D + row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer)); + } else { + row.then("-").color(ChatColor.GRAY); + } + } + } + ret.add(row); + } - // Add the faction key - if (Conf.showMapFactionKey) { - FancyMessage fRow = new FancyMessage(""); - for (String key : fList.keySet()) { - fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY); - } - ret.add(fRow); - } + // Add the faction key + if (Conf.showMapFactionKey) { + FancyMessage fRow = new FancyMessage(""); + for (String key : fList.keySet()) { + fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY); + } + ret.add(fRow); + } - return ret; - } + return ret; + } - //----------------------------------------------// - // Map generation - //----------------------------------------------// + //----------------------------------------------// + // Map generation + //----------------------------------------------// - private List oneLineToolTip(Faction faction, FPlayer to) { - return Arrays.asList(faction.describeTo(to)); - } + private List oneLineToolTip(Faction faction, FPlayer to) { + return Arrays.asList(faction.describeTo(to)); + } - @SuppressWarnings("unused") - private List getToolTip(Faction faction, FPlayer to) { - List ret = new ArrayList<>(); - List show = P.p.getConfig().getStringList("map"); + @SuppressWarnings("unused") + private List getToolTip(Faction faction, FPlayer to) { + List ret = new ArrayList<>(); + List show = P.p.getConfig().getStringList("map"); - if (!faction.isNormal()) { - String tag = faction.getTag(to); - // send header and that's all - String header = show.get(0); - if (TagReplacer.HEADER.contains(header)) { - ret.add(P.p.txt.titleize(tag)); - } else { - ret.add(P.p.txt.parse(TagReplacer.FACTION.replace(header, tag))); - } - return ret; // we only show header for non-normal factions - } + if (!faction.isNormal()) { + String tag = faction.getTag(to); + // send header and that's all + String header = show.get(0); + if (TagReplacer.HEADER.contains(header)) { + ret.add(P.p.txt.titleize(tag)); + } else { + ret.add(P.p.txt.parse(TagReplacer.FACTION.replace(header, tag))); + } + return ret; // we only show header for non-normal factions + } - for (String raw : show) { - // Hack to get rid of the extra underscores in title normally used to center tag - if (raw.contains("{header}")) { - raw = raw.replace("{header}", faction.getTag(to)); - } + for (String raw : show) { + // Hack to get rid of the extra underscores in title normally used to center tag + if (raw.contains("{header}")) { + raw = raw.replace("{header}", faction.getTag(to)); + } - String parsed = TagUtil.parsePlain(faction, to, raw); // use relations - if (parsed == null) { - continue; // Due to minimal f show. - } + String parsed = TagUtil.parsePlain(faction, to, raw); // use relations + if (parsed == null) { + continue; // Due to minimal f show. + } - if (TagUtil.hasFancy(parsed)) { - List fancy = TagUtil.parseFancy(faction, to, parsed); - if (fancy != null) { - for (FancyMessage msg : fancy) { - ret.add((P.p.txt.parse(msg.toOldMessageFormat()))); - } - } - continue; - } + if (TagUtil.hasFancy(parsed)) { + List fancy = TagUtil.parseFancy(faction, to, parsed); + if (fancy != null) { + for (FancyMessage msg : fancy) { + ret.add((P.p.txt.parse(msg.toOldMessageFormat()))); + } + } + continue; + } - if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { - if (parsed.contains("{ig}")) { - // replaces all variables with no home TL - parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); - } - if (parsed.contains("%")) { - parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. - } - ret.add(P.p.txt.parse(parsed)); - } - } + if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { + if (parsed.contains("{ig}")) { + // replaces all variables with no home TL + parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); + } + if (parsed.contains("%")) { + parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. + } + ret.add(P.p.txt.parse(parsed)); + } + } - return ret; - } + return ret; + } - public abstract void convertFrom(MemoryBoard old); + public abstract void convertFrom(MemoryBoard old); - public class MemoryBoardMap extends HashMap { - private static final long serialVersionUID = -6689617828610585368L; + public class MemoryBoardMap extends HashMap { + private static final long serialVersionUID = -6689617828610585368L; - Multimap factionToLandMap = HashMultimap.create(); + Multimap factionToLandMap = HashMultimap.create(); - @Override - public String put(FLocation floc, String factionId) { - String previousValue = super.put(floc, factionId); - if (previousValue != null) { - factionToLandMap.remove(previousValue, floc); - } + @Override + public String put(FLocation floc, String factionId) { + String previousValue = super.put(floc, factionId); + if (previousValue != null) { + factionToLandMap.remove(previousValue, floc); + } - factionToLandMap.put(factionId, floc); - return previousValue; - } + factionToLandMap.put(factionId, floc); + return previousValue; + } - @Override - public String remove(Object key) { - String result = super.remove(key); - if (result != null) { - FLocation floc = (FLocation) key; - factionToLandMap.remove(result, floc); - } + @Override + public String remove(Object key) { + String result = super.remove(key); + if (result != null) { + FLocation floc = (FLocation) key; + factionToLandMap.remove(result, floc); + } - return result; - } + return result; + } - @Override - public void clear() { - super.clear(); - factionToLandMap.clear(); - } + @Override + public void clear() { + super.clear(); + factionToLandMap.clear(); + } - public int getOwnedLandCount(String factionId) { - return factionToLandMap.get(factionId).size(); - } + public int getOwnedLandCount(String factionId) { + return factionToLandMap.get(factionId).size(); + } - public void removeFaction(String factionId) { - Collection flocations = factionToLandMap.removeAll(factionId); - for (FLocation floc : flocations) { - super.remove(floc); - } - } - } + public void removeFaction(String factionId) { + Collection flocations = factionToLandMap.removeAll(factionId); + for (FLocation floc : flocations) { + super.remove(floc); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java index 31e5243e..9e026bc7 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java @@ -41,1261 +41,1258 @@ import java.util.*; */ public abstract class MemoryFPlayer implements FPlayer { - protected HashMap commandCooldown = new HashMap<>(); - public boolean inVault = false; - protected String factionId; - protected Role role; - protected String title; - protected double power; - protected double powerBoost; - protected long lastPowerUpdateTime; - protected long lastLoginTime; - protected ChatMode chatMode; - protected boolean ignoreAllianceChat = false; - protected String id; - protected String name; - protected boolean monitorJoins; - protected boolean spyingChat = false; - protected boolean showScoreboard = true; - protected WarmUpUtil.Warmup warmup; - protected int warmupTask; - protected boolean isAdminBypassing = false; - protected int kills, deaths; - protected boolean willAutoLeave = true; - protected int mapHeight = 8; // default to old value - protected boolean isFlying = false; - protected boolean enteringPassword = false; - protected String enteringPasswordWarp = ""; - protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? - protected transient boolean mapAutoUpdating; - protected transient Faction autoClaimFor; - protected transient boolean autoSafeZoneEnabled; - protected transient boolean autoWarZoneEnabled; - protected transient boolean loginPvpDisabled; - protected transient long lastFrostwalkerMessage; - protected transient boolean shouldTakeFallDamage = true; - protected boolean isStealthEnabled = false; - protected boolean notificationsEnabled = true; - boolean inspectMode = false; - protected boolean isAlt = false; - - public void setAlt(boolean alt){ - this.isAlt = alt; - } - - public boolean isAlt() { - return isAlt; - } - - public MemoryFPlayer() { - } - - public MemoryFPlayer(String id) { - this.id = id; - this.isAlt = false; - this.resetFactionData(false); - this.power = Conf.powerPlayerStarting; - this.lastPowerUpdateTime = System.currentTimeMillis(); - this.lastLoginTime = System.currentTimeMillis(); - this.mapAutoUpdating = false; - this.autoClaimFor = null; - this.notificationsEnabled = true; - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; - this.powerBoost = 0.0; - this.getKills(); - this.getDeaths(); - this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", false); - this.mapHeight = Conf.mapHeight; - - if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) { - this.factionId = Conf.newPlayerStartingFactionID; - } - } - - public MemoryFPlayer(MemoryFPlayer other) { - this.factionId = other.factionId; - this.id = other.id; - this.isAlt = other.isAlt; - this.power = other.power; - this.lastLoginTime = other.lastLoginTime; - this.mapAutoUpdating = other.mapAutoUpdating; - this.autoClaimFor = other.autoClaimFor; - this.autoSafeZoneEnabled = other.autoSafeZoneEnabled; - this.autoWarZoneEnabled = other.autoWarZoneEnabled; - this.loginPvpDisabled = other.loginPvpDisabled; - this.powerBoost = other.powerBoost; - this.role = other.role; - this.title = other.title; - this.chatMode = other.chatMode; - this.spyingChat = other.spyingChat; - this.lastStoodAt = other.lastStoodAt; - this.getKills(); - this.getDeaths(); - this.isAdminBypassing = other.isAdminBypassing; - this.notificationsEnabled = other.notificationsEnabled; - this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", true); - this.mapHeight = Conf.mapHeight; - } - - - - public boolean isStealthEnabled() { - return this.isStealthEnabled; - } - - public void setStealth(boolean stealth) { - this.isStealthEnabled = stealth; - } - - public void login() { - this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); - this.deaths = getPlayer().getStatistic(Statistic.DEATHS); - } - - public void logout() { - this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); - this.deaths = getPlayer().getStatistic(Statistic.DEATHS); - } - - public int getCooldown(String cmd) { - int seconds = 0; - if (this.getPlayer().isOp()) - return 0; - if (commandCooldown.containsKey(cmd)) - seconds = (int) ((this.commandCooldown.get(cmd) - System.currentTimeMillis()) / 1000); - return seconds; - } - - public void setCooldown(String cmd, long cooldown) { - if (this.getPlayer().isOp()) - return; - - this.commandCooldown.put(cmd, cooldown); - } - - public boolean isCooldownEnded(String cmd) { - if (this.getPlayer().isOp()) - return true; - if (!commandCooldown.containsKey(cmd)) - return true; - else return commandCooldown.containsKey(cmd) && commandCooldown.get(cmd) <= System.currentTimeMillis(); - } - - - public Faction getFaction() { - if (this.factionId == null) { - this.factionId = "0"; - } - return Factions.getInstance().getFactionById(this.factionId); - } - - public void setFaction(Faction faction, boolean alt) { - Faction oldFaction = this.getFaction(); - if (oldFaction != null) { - if (this.isAlt()) { - oldFaction.removeAltPlayer(this); - } - - oldFaction.removeFPlayer(this); - } - if (alt) { - faction.addAltPlayer(this); - } else { - faction.addFPlayer(this); - } - this.factionId = faction.getId(); - } - - @Override - public void setNotificationsEnabled(boolean enabled) { - this.notificationsEnabled = enabled; - } - - @Override - public boolean hasNotificationsEnabled() { - return this.notificationsEnabled; - } - - public String getFactionId() { - return this.factionId; - } - - public boolean hasFaction() { - return !factionId.equals("0"); - } - - public void setMonitorJoins(boolean monitor) { - this.monitorJoins = monitor; - } - - public boolean isMonitoringJoins() { - return this.monitorJoins; - } - - public Role getRole() { - // Hack to fix null roles.. - if (role == null) { - this.role = Role.NORMAL; - } - - return this.role; - } - - public void setRole(Role role) { - this.role = role; - } - - public double getPowerBoost() { - return this.powerBoost; - } - - public void setPowerBoost(double powerBoost) { - this.powerBoost = powerBoost; - } - - public boolean willAutoLeave() { - return this.willAutoLeave; - } - - public void setAutoLeave(boolean willLeave) { - this.willAutoLeave = willLeave; - P.p.debug(name + " set autoLeave to " + willLeave); - } - - public long getLastFrostwalkerMessage() { - return this.lastFrostwalkerMessage; - } - - public void setLastFrostwalkerMessage() { - this.lastFrostwalkerMessage = System.currentTimeMillis(); - } - - public Faction getAutoClaimFor() { - return autoClaimFor; - } - - public void setAutoClaimFor(Faction faction) { - this.autoClaimFor = faction; - if (this.autoClaimFor != null) { - // TODO: merge these into same autoclaim - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - } - } - - public boolean isAutoSafeClaimEnabled() { - return autoSafeZoneEnabled; - } - - public void setIsAutoSafeClaimEnabled(boolean enabled) { - this.autoSafeZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoWarZoneEnabled = false; - } - } - - public boolean isAutoWarClaimEnabled() { - return autoWarZoneEnabled; - } - - public void setIsAutoWarClaimEnabled(boolean enabled) { - this.autoWarZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; - } - } - - public boolean isAdminBypassing() { - return this.isAdminBypassing; - } - - public boolean isVanished() { - return Essentials.isVanished(getPlayer()); - } - - public void setIsAdminBypassing(boolean val) { - this.isAdminBypassing = val; - } - - public ChatMode getChatMode() { - if (this.factionId.equals("0") || !Conf.factionOnlyChat) { - this.chatMode = ChatMode.PUBLIC; - } - return chatMode; - } - - public void setChatMode(ChatMode chatMode) { - this.chatMode = chatMode; - } - - public boolean isIgnoreAllianceChat() { - return ignoreAllianceChat; - } - - public void setIgnoreAllianceChat(boolean ignore) { - this.ignoreAllianceChat = ignore; - } - - public boolean isSpyingChat() { - return spyingChat; - } - - public void setSpyingChat(boolean chatSpying) { - this.spyingChat = chatSpying; - } - - // -------------------------------------------- // - // Getters And Setters - // -------------------------------------------- // - - // FIELD: account - public String getAccountId() { - return this.getId(); - } - - public void resetFactionData(boolean doSpoutUpdate) { - // clean up any territory ownership in old faction, if there is one - if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { - Faction currentFaction = this.getFaction(); - currentFaction.removeFPlayer(this); - if (currentFaction.isNormal()) { - currentFaction.clearClaimOwnership(this); - } - } - - this.factionId = "0"; // The default neutral faction - this.chatMode = ChatMode.PUBLIC; - this.role = Role.NORMAL; - this.title = ""; - this.autoClaimFor = null; - this.isAlt = false; - } - - public void resetFactionData() { - this.resetFactionData(true); - } - - public long getLastLoginTime() { - return lastLoginTime; - } - - public void setLastLoginTime(long lastLoginTime) { - losePowerFromBeingOffline(); - this.lastLoginTime = lastLoginTime; - this.lastPowerUpdateTime = lastLoginTime; - if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { - this.loginPvpDisabled = true; - } - } - - public boolean isMapAutoUpdating() { - return mapAutoUpdating; - } - - public void setMapAutoUpdating(boolean mapAutoUpdating) { - this.mapAutoUpdating = mapAutoUpdating; - } - - //----------------------------------------------// - // Title, Name, Faction Tag and Chat - //----------------------------------------------// - - // Base: - - public boolean hasLoginPvpDisabled() { - if (!loginPvpDisabled) { - return false; - } - if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { - this.loginPvpDisabled = false; - return false; - } - return true; - } - - public FLocation getLastStoodAt() { - return this.lastStoodAt; - } - - public void setLastStoodAt(FLocation flocation) { - this.lastStoodAt = flocation; - } - - public String getTitle() { - return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); - } - - public void setTitle(CommandSender sender, String title) { - // Check if the setter has it. - if (sender.hasPermission(Permission.TITLE_COLOR.node)) { - title = ChatColor.translateAlternateColorCodes('&', title); - } - - this.title = title; - } - - // Base concatenations: - - public String getName() { - if (this.name == null) { - // Older versions of FactionsUUID don't save the name, - // so `name` will be null the first time it's retrieved - // after updating - OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(getId())); - this.name = offline.getName() != null ? offline.getName() : getId(); - } - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTag() { - return this.hasFaction() ? this.getFaction().getTag() : ""; - } - - // Colored concatenations: - // These are used in information messages - - public String getNameAndSomething(String something) { - String ret = this.role.getPrefix(); - if (something.length() > 0) { - ret += something + " "; - } - ret += this.getName(); - return ret; - } - - public String getNameAndTitle() { - return this.getNameAndSomething(this.getTitle()); - } - - // Chat Tag: - // These are injected into the format of global chat messages. - - public String getNameAndTag() { - return this.getNameAndSomething(this.getTag()); - } - - public String getNameAndTitle(Faction faction) { - return this.getColorTo(faction) + this.getNameAndTitle(); - } - - public String getNameAndTitle(MemoryFPlayer fplayer) { - return this.getColorTo(fplayer) + this.getNameAndTitle(); - } - - public String getChatTag() { - return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); - } - - // Colored Chat Tag - public String getChatTag(Faction faction) { - return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : ""; - } - - // ------------------------------- - // Relation and relation colors - // ------------------------------- - - public String getChatTag(MemoryFPlayer fplayer) { - return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : ""; - } - - public int getKills() { - return isOnline() ? getPlayer().getStatistic(Statistic.PLAYER_KILLS) : this.kills; - } - - public int getDeaths() { - return isOnline() ? getPlayer().getStatistic(Statistic.DEATHS) : this.deaths; - - } - - @Override - public String describeTo(RelationParticipator that, boolean ucfirst) { - return RelationUtil.describeThatToMe(this, that, ucfirst); - } - - @Override - public String describeTo(RelationParticipator that) { - return RelationUtil.describeThatToMe(this, that); - } - - @Override - public Relation getRelationTo(RelationParticipator rp) { - return RelationUtil.getRelationTo(this, rp); - } - - @Override - public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { - return RelationUtil.getRelationTo(this, rp, ignorePeaceful); - } - - public Relation getRelationToLocation() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this); - } - - @Override - public ChatColor getColorTo(RelationParticipator rp) { - return RelationUtil.getColorOfThatToMe(this, rp); - } - - //----------------------------------------------// - // Health - //----------------------------------------------// - public void heal(int amnt) { - Player player = this.getPlayer(); - if (player == null) { - return; - } - player.setHealth(player.getHealth() + amnt); - } - - //----------------------------------------------// - // Power - //----------------------------------------------// - public double getPower() { - this.updatePower(); - return this.power; - } - - public void alterPower(double delta) { - this.power += delta; - if (this.power > this.getPowerMax()) { - this.power = this.getPowerMax(); - } else if (this.power < this.getPowerMin()) { - this.power = this.getPowerMin(); - } - } - - public double getPowerMax() { - return Conf.powerPlayerMax + this.powerBoost; - } - - public double getPowerMin() { - return Conf.powerPlayerMin + this.powerBoost; - } - - public int getPowerRounded() { - return (int) Math.round(this.getPower()); - } - - public int getPowerMaxRounded() { - return (int) Math.round(this.getPowerMax()); - } - - public int getPowerMinRounded() { - return (int) Math.round(this.getPowerMin()); - } - - public void updatePower() { - if (this.isOffline()) { - losePowerFromBeingOffline(); - if (!Conf.powerRegenOffline) { - return; - } - } else if (hasFaction() && getFaction().isPowerFrozen()) { - return; // Don't let power regen if faction power is frozen. - } - - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; - - Player thisPlayer = this.getPlayer(); - if (thisPlayer != null && thisPlayer.isDead()) { - return; // don't let dead players regain power until they respawn - } - - PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this); - Bukkit.getScheduler().runTask(P.p, () -> Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent)); - - if (!powerRegenEvent.isCancelled()) - this.alterPower(millisPassed * Conf.powerPerMinute / 60000); // millisPerMinute : 60 * 1000 - } - - public void losePowerFromBeingOffline() { - if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; - - double loss = millisPassed * Conf.powerOfflineLossPerDay / (24 * 60 * 60 * 1000); - if (this.power - loss < Conf.powerOfflineLossLimit) { - loss = this.power; - } - this.alterPower(-loss); - } - } - - public void onDeath() { - this.updatePower(); - this.alterPower(-Conf.powerPerDeath); - if (hasFaction()) { - getFaction().setLastDeath(System.currentTimeMillis()); - } - } - - //----------------------------------------------// - // Territory - //----------------------------------------------// - public boolean isInOwnTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)) == this.getFaction(); - } - - public boolean isInOthersTerritory() { - Faction factionHere = Board.getInstance().getFactionAt(new FLocation(this)); - return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); - } - - public boolean isInAllyTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); - } - - public boolean isInNeutralTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); - } - - public boolean isInEnemyTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); - } - - public void sendFactionHereMessage(Faction from) { - Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); - boolean showChat = true; - if (showInfoBoard(toShow)) { - FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); - showChat = P.p.getConfig().getBoolean("scoreboard.also-send-chat", true); - } - if (showChat) { - this.sendMessage(P.p.txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); - } - } - - // ------------------------------- - // Actions - // ------------------------------- - - /** - * Check if the scoreboard should be shown. Simple method to be used by above method. - * - * @param toShow Faction to be shown. - * @return true if should show, otherwise false. - */ - public boolean showInfoBoard(Faction toShow) { - return showScoreboard && !toShow.isWarZone() && !toShow.isWilderness() && !toShow.isSafeZone() && P.p.getConfig().contains("scoreboard.finfo") && P.p.getConfig().getBoolean("scoreboard.finfo-enabled", false) && FScoreboard.get(this) != null; - } - - @Override - public boolean showScoreboard() { - return this.showScoreboard; - } - - @Override - public void setShowScoreboard(boolean show) { - this.showScoreboard = show; - } - - public void leave(boolean makePay) { - Faction myFaction = this.getFaction(); - makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); - - if (myFaction == null) { - resetFactionData(); - return; - } - - boolean perm = myFaction.isPermanent(); - - if (!perm && this.getRole() == Role.LEADER && myFaction.getFPlayers().size() > 1) { - msg(TL.LEAVE_PASSADMIN); - return; - } - - if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { - msg(TL.LEAVE_NEGATIVEPOWER); - return; - } - - // if economy is enabled and they're not on the bypass list, make sure they can pay - if (makePay && !Econ.hasAtLeast(this, Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString())) { - return; - } - - FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); - Bukkit.getServer().getPluginManager().callEvent(leaveEvent); - if (leaveEvent.isCancelled()) { - return; - } - - // then make 'em pay (if applicable) - if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString(), TL.LEAVE_FORLEAVE.toString())) { - return; - } - - // Am I the last one in the faction? - if (myFaction.getFPlayers().size() == 1) { - // Transfer all money - if (Econ.shouldBeUsed()) { - Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); - } - } - - if (myFaction.isNormal()) { - for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { - fplayer.msg(TL.LEAVE_LEFT, this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); - } - - if (Conf.logFactionLeave) { - P.p.log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); - } - } - - myFaction.removeAnnouncements(this); - - if(this.isAlt()){ - myFaction.removeAltPlayer(this); - this.msg(TL.LEAVE_LEFT, this.describeTo(this, true), myFaction.describeTo(this)); - } - - this.resetFactionData(); - setFlying(false); - - if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { - // Remove this faction - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.LEAVE_DISBANDED, myFaction.describeTo(fplayer, true)); - } - - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(getPlayer(), myFaction.getId(), PlayerDisbandReason.LEAVE); - Bukkit.getPluginManager().callEvent(disbandEvent); - - Factions.getInstance().removeFaction(myFaction.getId()); - if (Conf.logFactionDisband) { - P.p.log(TL.LEAVE_DISBANDEDLOG.format(myFaction.getTag(), myFaction.getId(), this.getName())); - } - } - } - - public boolean canClaimForFaction(Faction forFaction) { - return this.isAdminBypassing() || !forFaction.isWilderness() && (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())); - } - - public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { - return canClaimForFactionAtLocation(forFaction, new FLocation(location), notifyFailure); - } - - public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) { - String error = null; - Faction myFaction = getFaction(); - Faction currentFaction = Board.getInstance().getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); - int factionBuffer = P.p.getConfig().getInt("hcf.buffer-zone", 0); - int worldBuffer = P.p.getConfig().getInt("world-border.buffer", 0); - - if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { - // Checks for WorldGuard regions in the chunk attempting to be claimed - error = P.p.txt.parse(TL.CLAIM_PROTECTED.toString()); - } else if (flocation.isOutsideWorldBorder(P.p.getConfig().getInt("world-border.buffer", 0))) { - error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } else if (Conf.useWorldConfigurationsAsWhitelist != Conf.worldsNoClaiming.contains(flocation.getWorldName())) { - error = P.p.txt.parse(TL.CLAIM_DISABLED.toString()); - } else if (this.isAdminBypassing()) { - return true; - } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { - return true; - } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { - return true; - } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW) { - return true; - } else if (myFaction != forFaction) { - error = P.p.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); - } else if (forFaction == currentFaction) { - error = P.p.txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); - } else if (this.getRole().value < Role.MODERATOR.value) { - error = P.p.txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); - } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { - error = P.p.txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); - } else if (currentFaction.isSafeZone()) { - error = P.p.txt.parse(TL.CLAIM_SAFEZONE.toString()); - } else if (currentFaction.isWarZone()) { - error = P.p.txt.parse(TL.CLAIM_WARZONE.toString()); - } else if (P.p.getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { - error = P.p.txt.parse(TL.CLAIM_POWER.toString()); - } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { - error = P.p.txt.parse(TL.CLAIM_LIMIT.toString()); - } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { - error = P.p.txt.parse(TL.CLAIM_ALLY.toString()); - } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { - if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { - error = P.p.txt.parse(TL.CLAIM_CONTIGIOUS.toString()); - } else { - error = P.p.txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); - } - } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { - error = P.p.txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); - } else if (flocation.isOutsideWorldBorder(worldBuffer)) { - if (worldBuffer > 0) { - error = P.p.txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); - } else { - error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } - } else if (currentFaction.isNormal()) { - if (myFaction.isPeaceful()) { - error = P.p.txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); - } else if (currentFaction.isPeaceful()) { - error = P.p.txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); - } else if (!currentFaction.hasLandInflation()) { - // TODO more messages WARN current faction most importantly - error = P.p.txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); - } else if (currentFaction.hasLandInflation() && !P.p.getConfig().getBoolean("hcf.allow-overclaim", true)) { - // deny over claim when it normally would be allowed. - error = P.p.txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); - } else if (!Board.getInstance().isBorderLocation(flocation)) { - error = P.p.txt.parse(TL.CLAIM_BORDER.toString()); - } - } - // TODO: Add more else if statements. - - if (notifyFailure && error != null) { - msg(error); - } - return error == null; - } - - public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { - return attemptClaim(forFaction, new FLocation(location), notifyFailure); - } - - - public boolean shouldBeSaved() { - return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); - } - - public void msg(String str, Object... args) { - this.sendMessage(P.p.txt.parse(str, args)); - } - - public void msg(TL translation, Object... args) { - this.msg(translation.toString(), args); - } - - public Player getPlayer() { - return Bukkit.getPlayer(UUID.fromString(this.getId())); - } - - public boolean isOnline() { - return this.getPlayer() != null; - } - - // make sure target player should be able to detect that this player is online - public boolean isOnlineAndVisibleTo(Player player) { - Player target = this.getPlayer(); - return target != null && player.canSee(target); - } - - public boolean isOffline() { - return !isOnline(); - } - - public boolean isFlying() { - return isFlying; - } - - public void setFlying(boolean fly) { - setFFlying(fly, false); - } - - public void setFFlying(boolean fly, boolean damage) { - Player player = getPlayer(); - if(player == null) return; - - player.setAllowFlight(fly); - player.setFlying(fly); - - if (!damage) { - msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); - if (!fly) { - sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", P.p.getConfig().getInt("fly-falldamage-cooldown", 3) + "")); - } - - } else { - msg(TL.COMMAND_FLY_DAMAGE); - } - - // If leaving fly mode, don't let them take fall damage for x seconds. - if (!fly) { - int cooldown = P.p.getConfig().getInt("fly-falldamage-cooldown", 3); - CmdFly.flyMap.remove(player.getName()); - - // If the value is 0 or lower, make them take fall damage. - // Otherwise, start a timer and have this cancel after a few seconds. - // Short task so we're just doing it in method. Not clean but eh. - if (cooldown > 0) { - setTakeFallDamage(false); - Bukkit.getScheduler().runTaskLater(P.p, () -> setTakeFallDamage(true), 20L * cooldown); - } - } - - isFlying = fly; - } - - public boolean isInVault() { - return inVault; - } - - public void setInVault(boolean status) { - inVault = status; - } - - public boolean canFlyAtLocation() { - return canFlyAtLocation(lastStoodAt); - } - - public boolean canFlyAtLocation(FLocation location) { - Faction faction = Board.getInstance().getFactionAt(location); - if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) { - return true; - } - - Access access = faction.getAccess(this, PermissableAction.FLY); - return access == null || access == Access.UNDEFINED || access == Access.ALLOW; - } - - public boolean shouldTakeFallDamage() { - return this.shouldTakeFallDamage; - } - - public void setTakeFallDamage(boolean fallDamage) { - this.shouldTakeFallDamage = fallDamage; - } - - public boolean isEnteringPassword() { - return enteringPassword; - } - - public void setEnteringPassword(boolean toggle, String warp) { - enteringPassword = toggle; - enteringPasswordWarp = warp; - } - - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // - - public String getEnteringWarp() { - return enteringPasswordWarp; - } - - public void sendMessage(String msg) { - if (msg.contains("{null}")) { - return; // user wants this message to not send - } - if (msg.contains("/n/")) { - for (String s : msg.split("/n/")) { - sendMessage(s); - } - return; - } - Player player = this.getPlayer(); - if (player == null) { - return; - } - player.sendMessage(msg); - } - - public void sendMessage(List msgs) { - for (String msg : msgs) { - this.sendMessage(msg); - } - } - - public void sendFancyMessage(FancyMessage message) { - Player player = getPlayer(); - if (player == null || !player.isOnGround()) { - return; - } - - message.send(player); - } - - public void sendFancyMessage(List messages) { - Player player = getPlayer(); - if (player == null) { - return; - } - - for (FancyMessage msg : messages) { - msg.send(player); - } - } - - public int getMapHeight() { - if (this.mapHeight < 1) { - this.mapHeight = Conf.mapHeight; - } - - return this.mapHeight; - } - - public void setMapHeight(int height) { - this.mapHeight = height > (Conf.mapHeight * 2) ? (Conf.mapHeight * 2) : height; - } - - public String getNameAndTitle(FPlayer fplayer) { - return this.getColorTo(fplayer) + this.getNameAndTitle(); - } - - @Override - public String getChatTag(FPlayer fplayer) { - return this.hasFaction() ? this.getRelationTo(fplayer).getColor() + getChatTag() : ""; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - public abstract void remove(); - - @Override - public void clearWarmup() { - if (warmup != null) { - Bukkit.getScheduler().cancelTask(warmupTask); - this.stopWarmup(); - } - } - - @Override - public void stopWarmup() { - warmup = null; - } - - @Override - public boolean isWarmingUp() { - return warmup != null; - } - - @Override - public WarmUpUtil.Warmup getWarmupType() { - return warmup; - } - - @Override - public void addWarmup(WarmUpUtil.Warmup warmup, int taskId) { - if (this.warmup != null) { - this.clearWarmup(); - } - this.warmup = warmup; - this.warmupTask = taskId; - } - - @Override - public boolean checkIfNearbyEnemies() { - Player me = this.getPlayer(); - - if (me == null) { - return false; - } - - int radius = Conf.stealthFlyCheckRadius; - for (Entity e : me.getNearbyEntities(radius, 255, radius)) { - if (e == null) { - continue; - } - if (e instanceof Player) { - Player eplayer = (((Player) e).getPlayer()); - if (eplayer == null) { - continue; - } - FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); - if (efplayer == null) { - continue; - } - if (efplayer.isVanished()) continue; - if (this.getRelationTo(efplayer).equals(Relation.ENEMY) && !efplayer.isStealthEnabled()) { - setFlying(false); - msg(TL.COMMAND_FLY_ENEMY_NEAR); - Bukkit.getServer().getPluginManager().callEvent(new FPlayerStoppedFlying(this)); - return true; - } - } - } - return false; - } - - @Override - public Boolean canflyinWilderness() { - return getPlayer().hasPermission("factions.fly.wilderness"); - } - - @Override - public Boolean canflyinWarzone() { - return getPlayer().hasPermission("factions.fly.warzone"); - - } - - @Override - public Boolean canflyinSafezone() { - return getPlayer().hasPermission("factions.fly.safezone"); - - } - - @Override - public Boolean canflyinEnemy() { - return getPlayer().hasPermission("factions.fly.enemy"); - - } - - @Override - public Boolean canflyinAlly() { - return getPlayer().hasPermission("factions.fly.ally"); - - } - - @Override - public Boolean canflyinTruce() { - return getPlayer().hasPermission("factions.fly.truce"); - - } - - @Override - public Boolean canflyinNeutral() { - return getPlayer().hasPermission("factions.fly.neutral"); - - } - - @Override - public boolean isInspectMode() { - return inspectMode; - } - - @Override - public void setInspectMode(boolean status) { - inspectMode = status; - } - - public boolean attemptClaim(Faction forFaction, FLocation flocation, boolean notifyFailure) { - // notifyFailure is false if called by auto-claim; no need to notify on every failure for it - // return value is false on failure, true on success - Faction currentFaction = Board.getInstance().getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); - - if (!this.canClaimForFactionAtLocation(forFaction, flocation, notifyFailure)) { - return false; - } - - // if economy is enabled and they're not on the bypass list, make sure they can pay - boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); - double cost = 0.0; - EconomyParticipator payee = null; - if (mustPay) { - cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); - - - if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, forFaction)) { - cost += Conf.econClaimUnconnectedFee; - } - - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) { - payee = this.getFaction(); - } else { - payee = this; - } - - if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { - return false; - } - } - - LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); - Bukkit.getScheduler().runTask(P.p, () -> Bukkit.getPluginManager().callEvent(claimEvent)); - if (claimEvent.isCancelled()) { - return false; - } - - // then make 'em pay (if applicable) - if (mustPay && !Econ.modifyMoney(payee, -cost, TL.CLAIM_TOCLAIM.toString(), TL.CLAIM_FORCLAIM.toString())) { - return false; - } - - // Was an over claim - if (mustPay && currentFaction.isNormal() && currentFaction.hasLandInflation()) { - // Give them money for over claiming. - Econ.modifyMoney(payee, Conf.econOverclaimRewardMultiplier, TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); - } - - // announce success - Set informTheseFPlayers = new HashSet<>(); - informTheseFPlayers.add(this); - informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); - for (FPlayer fp : informTheseFPlayers) { - fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); - } - - Board.getInstance().setFactionAt(forFaction, flocation); - - if (Conf.logLandClaims) { - P.p.log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); - } - - return true; - } - - - - @Override - public String getRolePrefix() { - - switch (getRole()) { - case RECRUIT: - return Conf.prefixRecruit; - case NORMAL: - return Conf.prefixNormal; - case MODERATOR: - return Conf.prefixMod; - case COLEADER: - return Conf.prefixCoLeader; - case LEADER: - return Conf.prefixLeader; - } - - return null; - } - - @Override - public boolean hasMoney(int amt) { - Economy econ = P.p.getEcon(); - if (econ.getBalance(getPlayer()) >= amt) { - return true; - } else { - getPlayer().closeInventory(); - msg(TL.GENERIC_NOTENOUGHMONEY); - return false; - } - } - - public String commas(final double amount) { - final DecimalFormat formatter = new DecimalFormat("#,###.00"); - return formatter.format(amount); - } - - @Override - public void takeMoney(int amt) { - if (hasMoney(amt)) { - Economy econ = P.p.getEcon(); - econ.withdrawPlayer(getPlayer(), amt); - sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", commas(amt))); - } - } + public boolean inVault = false; + protected HashMap commandCooldown = new HashMap<>(); + protected String factionId; + protected Role role; + protected String title; + protected double power; + protected double powerBoost; + protected long lastPowerUpdateTime; + protected long lastLoginTime; + protected ChatMode chatMode; + protected boolean ignoreAllianceChat = false; + protected String id; + protected String name; + protected boolean monitorJoins; + protected boolean spyingChat = false; + protected boolean showScoreboard = true; + protected WarmUpUtil.Warmup warmup; + protected int warmupTask; + protected boolean isAdminBypassing = false; + protected int kills, deaths; + protected boolean willAutoLeave = true; + protected int mapHeight = 8; // default to old value + protected boolean isFlying = false; + protected boolean enteringPassword = false; + protected String enteringPasswordWarp = ""; + protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? + protected transient boolean mapAutoUpdating; + protected transient Faction autoClaimFor; + protected transient boolean autoSafeZoneEnabled; + protected transient boolean autoWarZoneEnabled; + protected transient boolean loginPvpDisabled; + protected transient long lastFrostwalkerMessage; + protected transient boolean shouldTakeFallDamage = true; + protected boolean isStealthEnabled = false; + protected boolean notificationsEnabled = true; + protected boolean isAlt = false; + boolean inspectMode = false; + + public MemoryFPlayer() { + } + + public MemoryFPlayer(String id) { + this.id = id; + this.isAlt = false; + this.resetFactionData(false); + this.power = Conf.powerPlayerStarting; + this.lastPowerUpdateTime = System.currentTimeMillis(); + this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; + this.autoClaimFor = null; + this.notificationsEnabled = true; + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; + this.powerBoost = 0.0; + this.getKills(); + this.getDeaths(); + this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", false); + this.mapHeight = Conf.mapHeight; + + if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) { + this.factionId = Conf.newPlayerStartingFactionID; + } + } + + public MemoryFPlayer(MemoryFPlayer other) { + this.factionId = other.factionId; + this.id = other.id; + this.isAlt = other.isAlt; + this.power = other.power; + this.lastLoginTime = other.lastLoginTime; + this.mapAutoUpdating = other.mapAutoUpdating; + this.autoClaimFor = other.autoClaimFor; + this.autoSafeZoneEnabled = other.autoSafeZoneEnabled; + this.autoWarZoneEnabled = other.autoWarZoneEnabled; + this.loginPvpDisabled = other.loginPvpDisabled; + this.powerBoost = other.powerBoost; + this.role = other.role; + this.title = other.title; + this.chatMode = other.chatMode; + this.spyingChat = other.spyingChat; + this.lastStoodAt = other.lastStoodAt; + this.getKills(); + this.getDeaths(); + this.isAdminBypassing = other.isAdminBypassing; + this.notificationsEnabled = other.notificationsEnabled; + this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", true); + this.mapHeight = Conf.mapHeight; + } + + public boolean isAlt() { + return isAlt; + } + + public void setAlt(boolean alt) { + this.isAlt = alt; + } + + public boolean isStealthEnabled() { + return this.isStealthEnabled; + } + + public void setStealth(boolean stealth) { + this.isStealthEnabled = stealth; + } + + public void login() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public void logout() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public int getCooldown(String cmd) { + int seconds = 0; + if (this.getPlayer().isOp()) + return 0; + if (commandCooldown.containsKey(cmd)) + seconds = (int) ((this.commandCooldown.get(cmd) - System.currentTimeMillis()) / 1000); + return seconds; + } + + public void setCooldown(String cmd, long cooldown) { + if (this.getPlayer().isOp()) + return; + + this.commandCooldown.put(cmd, cooldown); + } + + public boolean isCooldownEnded(String cmd) { + if (this.getPlayer().isOp()) + return true; + if (!commandCooldown.containsKey(cmd)) + return true; + else return commandCooldown.containsKey(cmd) && commandCooldown.get(cmd) <= System.currentTimeMillis(); + } + + + public Faction getFaction() { + if (this.factionId == null) { + this.factionId = "0"; + } + return Factions.getInstance().getFactionById(this.factionId); + } + + public void setFaction(Faction faction, boolean alt) { + Faction oldFaction = this.getFaction(); + if (oldFaction != null) { + if (this.isAlt()) { + oldFaction.removeAltPlayer(this); + } + + oldFaction.removeFPlayer(this); + } + if (alt) { + faction.addAltPlayer(this); + } else { + faction.addFPlayer(this); + } + this.factionId = faction.getId(); + } + + @Override + public void setNotificationsEnabled(boolean enabled) { + this.notificationsEnabled = enabled; + } + + @Override + public boolean hasNotificationsEnabled() { + return this.notificationsEnabled; + } + + public String getFactionId() { + return this.factionId; + } + + public boolean hasFaction() { + return !factionId.equals("0"); + } + + public void setMonitorJoins(boolean monitor) { + this.monitorJoins = monitor; + } + + public boolean isMonitoringJoins() { + return this.monitorJoins; + } + + public Role getRole() { + // Hack to fix null roles.. + if (role == null) { + this.role = Role.NORMAL; + } + + return this.role; + } + + public void setRole(Role role) { + this.role = role; + } + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + public boolean willAutoLeave() { + return this.willAutoLeave; + } + + public void setAutoLeave(boolean willLeave) { + this.willAutoLeave = willLeave; + P.p.debug(name + " set autoLeave to " + willLeave); + } + + public long getLastFrostwalkerMessage() { + return this.lastFrostwalkerMessage; + } + + public void setLastFrostwalkerMessage() { + this.lastFrostwalkerMessage = System.currentTimeMillis(); + } + + public Faction getAutoClaimFor() { + return autoClaimFor; + } + + public void setAutoClaimFor(Faction faction) { + this.autoClaimFor = faction; + if (this.autoClaimFor != null) { + // TODO: merge these into same autoclaim + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoSafeClaimEnabled() { + return autoSafeZoneEnabled; + } + + public void setIsAutoSafeClaimEnabled(boolean enabled) { + this.autoSafeZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoWarClaimEnabled() { + return autoWarZoneEnabled; + } + + public void setIsAutoWarClaimEnabled(boolean enabled) { + this.autoWarZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + } + } + + public boolean isAdminBypassing() { + return this.isAdminBypassing; + } + + public boolean isVanished() { + return Essentials.isVanished(getPlayer()); + } + + public void setIsAdminBypassing(boolean val) { + this.isAdminBypassing = val; + } + + public ChatMode getChatMode() { + if (this.factionId.equals("0") || !Conf.factionOnlyChat) { + this.chatMode = ChatMode.PUBLIC; + } + return chatMode; + } + + public void setChatMode(ChatMode chatMode) { + this.chatMode = chatMode; + } + + public boolean isIgnoreAllianceChat() { + return ignoreAllianceChat; + } + + public void setIgnoreAllianceChat(boolean ignore) { + this.ignoreAllianceChat = ignore; + } + + public boolean isSpyingChat() { + return spyingChat; + } + + public void setSpyingChat(boolean chatSpying) { + this.spyingChat = chatSpying; + } + + // -------------------------------------------- // + // Getters And Setters + // -------------------------------------------- // + + // FIELD: account + public String getAccountId() { + return this.getId(); + } + + public void resetFactionData(boolean doSpoutUpdate) { + // clean up any territory ownership in old faction, if there is one + if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { + Faction currentFaction = this.getFaction(); + currentFaction.removeFPlayer(this); + if (currentFaction.isNormal()) { + currentFaction.clearClaimOwnership(this); + } + } + + this.factionId = "0"; // The default neutral faction + this.chatMode = ChatMode.PUBLIC; + this.role = Role.NORMAL; + this.title = ""; + this.autoClaimFor = null; + this.isAlt = false; + } + + public void resetFactionData() { + this.resetFactionData(true); + } + + public long getLastLoginTime() { + return lastLoginTime; + } + + public void setLastLoginTime(long lastLoginTime) { + losePowerFromBeingOffline(); + this.lastLoginTime = lastLoginTime; + this.lastPowerUpdateTime = lastLoginTime; + if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { + this.loginPvpDisabled = true; + } + } + + public boolean isMapAutoUpdating() { + return mapAutoUpdating; + } + + public void setMapAutoUpdating(boolean mapAutoUpdating) { + this.mapAutoUpdating = mapAutoUpdating; + } + + //----------------------------------------------// + // Title, Name, Faction Tag and Chat + //----------------------------------------------// + + // Base: + + public boolean hasLoginPvpDisabled() { + if (!loginPvpDisabled) { + return false; + } + if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { + this.loginPvpDisabled = false; + return false; + } + return true; + } + + public FLocation getLastStoodAt() { + return this.lastStoodAt; + } + + public void setLastStoodAt(FLocation flocation) { + this.lastStoodAt = flocation; + } + + public String getTitle() { + return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); + } + + public void setTitle(CommandSender sender, String title) { + // Check if the setter has it. + if (sender.hasPermission(Permission.TITLE_COLOR.node)) { + title = ChatColor.translateAlternateColorCodes('&', title); + } + + this.title = title; + } + + // Base concatenations: + + public String getName() { + if (this.name == null) { + // Older versions of FactionsUUID don't save the name, + // so `name` will be null the first time it's retrieved + // after updating + OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(getId())); + this.name = offline.getName() != null ? offline.getName() : getId(); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTag() { + return this.hasFaction() ? this.getFaction().getTag() : ""; + } + + // Colored concatenations: + // These are used in information messages + + public String getNameAndSomething(String something) { + String ret = this.role.getPrefix(); + if (something.length() > 0) { + ret += something + " "; + } + ret += this.getName(); + return ret; + } + + public String getNameAndTitle() { + return this.getNameAndSomething(this.getTitle()); + } + + // Chat Tag: + // These are injected into the format of global chat messages. + + public String getNameAndTag() { + return this.getNameAndSomething(this.getTag()); + } + + public String getNameAndTitle(Faction faction) { + return this.getColorTo(faction) + this.getNameAndTitle(); + } + + public String getNameAndTitle(MemoryFPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + public String getChatTag() { + return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); + } + + // Colored Chat Tag + public String getChatTag(Faction faction) { + return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : ""; + } + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + public String getChatTag(MemoryFPlayer fplayer) { + return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : ""; + } + + public int getKills() { + return isOnline() ? getPlayer().getStatistic(Statistic.PLAYER_KILLS) : this.kills; + } + + public int getDeaths() { + return isOnline() ? getPlayer().getStatistic(Statistic.DEATHS) : this.deaths; + + } + + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } + + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } + + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } + + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } + + public Relation getRelationToLocation() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this); + } + + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } + + //----------------------------------------------// + // Health + //----------------------------------------------// + public void heal(int amnt) { + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.setHealth(player.getHealth() + amnt); + } + + //----------------------------------------------// + // Power + //----------------------------------------------// + public double getPower() { + this.updatePower(); + return this.power; + } + + public void alterPower(double delta) { + this.power += delta; + if (this.power > this.getPowerMax()) { + this.power = this.getPowerMax(); + } else if (this.power < this.getPowerMin()) { + this.power = this.getPowerMin(); + } + } + + public double getPowerMax() { + return Conf.powerPlayerMax + this.powerBoost; + } + + public double getPowerMin() { + return Conf.powerPlayerMin + this.powerBoost; + } + + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } + + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } + + public int getPowerMinRounded() { + return (int) Math.round(this.getPowerMin()); + } + + public void updatePower() { + if (this.isOffline()) { + losePowerFromBeingOffline(); + if (!Conf.powerRegenOffline) { + return; + } + } else if (hasFaction() && getFaction().isPowerFrozen()) { + return; // Don't let power regen if faction power is frozen. + } + + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; + + Player thisPlayer = this.getPlayer(); + if (thisPlayer != null && thisPlayer.isDead()) { + return; // don't let dead players regain power until they respawn + } + + PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this); + Bukkit.getScheduler().runTask(P.p, () -> Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent)); + + if (!powerRegenEvent.isCancelled()) + this.alterPower(millisPassed * Conf.powerPerMinute / 60000); // millisPerMinute : 60 * 1000 + } + + public void losePowerFromBeingOffline() { + if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; + + double loss = millisPassed * Conf.powerOfflineLossPerDay / (24 * 60 * 60 * 1000); + if (this.power - loss < Conf.powerOfflineLossLimit) { + loss = this.power; + } + this.alterPower(-loss); + } + } + + public void onDeath() { + this.updatePower(); + this.alterPower(-Conf.powerPerDeath); + if (hasFaction()) { + getFaction().setLastDeath(System.currentTimeMillis()); + } + } + + //----------------------------------------------// + // Territory + //----------------------------------------------// + public boolean isInOwnTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)) == this.getFaction(); + } + + public boolean isInOthersTerritory() { + Faction factionHere = Board.getInstance().getFactionAt(new FLocation(this)); + return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); + } + + public boolean isInAllyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); + } + + public boolean isInNeutralTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); + } + + public boolean isInEnemyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); + } + + public void sendFactionHereMessage(Faction from) { + Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); + boolean showChat = true; + if (showInfoBoard(toShow)) { + FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); + showChat = P.p.getConfig().getBoolean("scoreboard.also-send-chat", true); + } + if (showChat) { + this.sendMessage(P.p.txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); + } + } + + // ------------------------------- + // Actions + // ------------------------------- + + /** + * Check if the scoreboard should be shown. Simple method to be used by above method. + * + * @param toShow Faction to be shown. + * @return true if should show, otherwise false. + */ + public boolean showInfoBoard(Faction toShow) { + return showScoreboard && !toShow.isWarZone() && !toShow.isWilderness() && !toShow.isSafeZone() && P.p.getConfig().contains("scoreboard.finfo") && P.p.getConfig().getBoolean("scoreboard.finfo-enabled", false) && FScoreboard.get(this) != null; + } + + @Override + public boolean showScoreboard() { + return this.showScoreboard; + } + + @Override + public void setShowScoreboard(boolean show) { + this.showScoreboard = show; + } + + public void leave(boolean makePay) { + Faction myFaction = this.getFaction(); + makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); + + if (myFaction == null) { + resetFactionData(); + return; + } + + boolean perm = myFaction.isPermanent(); + + if (!perm && this.getRole() == Role.LEADER && myFaction.getFPlayers().size() > 1) { + msg(TL.LEAVE_PASSADMIN); + return; + } + + if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { + msg(TL.LEAVE_NEGATIVEPOWER); + return; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + if (makePay && !Econ.hasAtLeast(this, Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString())) { + return; + } + + FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); + Bukkit.getServer().getPluginManager().callEvent(leaveEvent); + if (leaveEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString(), TL.LEAVE_FORLEAVE.toString())) { + return; + } + + // Am I the last one in the faction? + if (myFaction.getFPlayers().size() == 1) { + // Transfer all money + if (Econ.shouldBeUsed()) { + Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); + } + } + + if (myFaction.isNormal()) { + for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { + fplayer.msg(TL.LEAVE_LEFT, this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); + } + + if (Conf.logFactionLeave) { + P.p.log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); + } + } + + myFaction.removeAnnouncements(this); + + if (this.isAlt()) { + myFaction.removeAltPlayer(this); + this.msg(TL.LEAVE_LEFT, this.describeTo(this, true), myFaction.describeTo(this)); + } + + this.resetFactionData(); + setFlying(false); + + if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { + // Remove this faction + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.LEAVE_DISBANDED, myFaction.describeTo(fplayer, true)); + } + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(getPlayer(), myFaction.getId(), PlayerDisbandReason.LEAVE); + Bukkit.getPluginManager().callEvent(disbandEvent); + + Factions.getInstance().removeFaction(myFaction.getId()); + if (Conf.logFactionDisband) { + P.p.log(TL.LEAVE_DISBANDEDLOG.format(myFaction.getTag(), myFaction.getId(), this.getName())); + } + } + } + + public boolean canClaimForFaction(Faction forFaction) { + return this.isAdminBypassing() || !forFaction.isWilderness() && (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { + return canClaimForFactionAtLocation(forFaction, new FLocation(location), notifyFailure); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) { + String error = null; + Faction myFaction = getFaction(); + Faction currentFaction = Board.getInstance().getFactionAt(flocation); + int ownedLand = forFaction.getLandRounded(); + int factionBuffer = P.p.getConfig().getInt("hcf.buffer-zone", 0); + int worldBuffer = P.p.getConfig().getInt("world-border.buffer", 0); + + if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { + // Checks for WorldGuard regions in the chunk attempting to be claimed + error = P.p.txt.parse(TL.CLAIM_PROTECTED.toString()); + } else if (flocation.isOutsideWorldBorder(P.p.getConfig().getInt("world-border.buffer", 0))) { + error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } else if (Conf.useWorldConfigurationsAsWhitelist != Conf.worldsNoClaiming.contains(flocation.getWorldName())) { + error = P.p.txt.parse(TL.CLAIM_DISABLED.toString()); + } else if (this.isAdminBypassing()) { + return true; + } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { + return true; + } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { + return true; + } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW) { + return true; + } else if (myFaction != forFaction) { + error = P.p.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); + } else if (forFaction == currentFaction) { + error = P.p.txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); + } else if (this.getRole().value < Role.MODERATOR.value) { + error = P.p.txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); + } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { + error = P.p.txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); + } else if (currentFaction.isSafeZone()) { + error = P.p.txt.parse(TL.CLAIM_SAFEZONE.toString()); + } else if (currentFaction.isWarZone()) { + error = P.p.txt.parse(TL.CLAIM_WARZONE.toString()); + } else if (P.p.getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { + error = P.p.txt.parse(TL.CLAIM_POWER.toString()); + } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { + error = P.p.txt.parse(TL.CLAIM_LIMIT.toString()); + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + error = P.p.txt.parse(TL.CLAIM_ALLY.toString()); + } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { + if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { + error = P.p.txt.parse(TL.CLAIM_CONTIGIOUS.toString()); + } else { + error = P.p.txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); + } + } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { + error = P.p.txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); + } else if (flocation.isOutsideWorldBorder(worldBuffer)) { + if (worldBuffer > 0) { + error = P.p.txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); + } else { + error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } + } else if (currentFaction.isNormal()) { + if (myFaction.isPeaceful()) { + error = P.p.txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); + } else if (currentFaction.isPeaceful()) { + error = P.p.txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); + } else if (!currentFaction.hasLandInflation()) { + // TODO more messages WARN current faction most importantly + error = P.p.txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); + } else if (currentFaction.hasLandInflation() && !P.p.getConfig().getBoolean("hcf.allow-overclaim", true)) { + // deny over claim when it normally would be allowed. + error = P.p.txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); + } else if (!Board.getInstance().isBorderLocation(flocation)) { + error = P.p.txt.parse(TL.CLAIM_BORDER.toString()); + } + } + // TODO: Add more else if statements. + + if (notifyFailure && error != null) { + msg(error); + } + return error == null; + } + + public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { + return attemptClaim(forFaction, new FLocation(location), notifyFailure); + } + + + public boolean shouldBeSaved() { + return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); + } + + public void msg(String str, Object... args) { + this.sendMessage(P.p.txt.parse(str, args)); + } + + public void msg(TL translation, Object... args) { + this.msg(translation.toString(), args); + } + + public Player getPlayer() { + return Bukkit.getPlayer(UUID.fromString(this.getId())); + } + + public boolean isOnline() { + return this.getPlayer() != null; + } + + // make sure target player should be able to detect that this player is online + public boolean isOnlineAndVisibleTo(Player player) { + Player target = this.getPlayer(); + return target != null && player.canSee(target); + } + + public boolean isOffline() { + return !isOnline(); + } + + public boolean isFlying() { + return isFlying; + } + + public void setFlying(boolean fly) { + setFFlying(fly, false); + } + + public void setFFlying(boolean fly, boolean damage) { + Player player = getPlayer(); + if (player == null) return; + + player.setAllowFlight(fly); + player.setFlying(fly); + + if (!damage) { + msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); + if (!fly) { + sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", P.p.getConfig().getInt("fly-falldamage-cooldown", 3) + "")); + } + + } else { + msg(TL.COMMAND_FLY_DAMAGE); + } + + // If leaving fly mode, don't let them take fall damage for x seconds. + if (!fly) { + int cooldown = P.p.getConfig().getInt("fly-falldamage-cooldown", 3); + CmdFly.flyMap.remove(player.getName()); + + // If the value is 0 or lower, make them take fall damage. + // Otherwise, start a timer and have this cancel after a few seconds. + // Short task so we're just doing it in method. Not clean but eh. + if (cooldown > 0) { + setTakeFallDamage(false); + Bukkit.getScheduler().runTaskLater(P.p, () -> setTakeFallDamage(true), 20L * cooldown); + } + } + + isFlying = fly; + } + + public boolean isInVault() { + return inVault; + } + + public void setInVault(boolean status) { + inVault = status; + } + + public boolean canFlyAtLocation() { + return canFlyAtLocation(lastStoodAt); + } + + public boolean canFlyAtLocation(FLocation location) { + Faction faction = Board.getInstance().getFactionAt(location); + if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) { + return true; + } + + Access access = faction.getAccess(this, PermissableAction.FLY); + return access == null || access == Access.UNDEFINED || access == Access.ALLOW; + } + + public boolean shouldTakeFallDamage() { + return this.shouldTakeFallDamage; + } + + public void setTakeFallDamage(boolean fallDamage) { + this.shouldTakeFallDamage = fallDamage; + } + + public boolean isEnteringPassword() { + return enteringPassword; + } + + public void setEnteringPassword(boolean toggle, String warp) { + enteringPassword = toggle; + enteringPasswordWarp = warp; + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public String getEnteringWarp() { + return enteringPasswordWarp; + } + + public void sendMessage(String msg) { + if (msg.contains("{null}")) { + return; // user wants this message to not send + } + if (msg.contains("/n/")) { + for (String s : msg.split("/n/")) { + sendMessage(s); + } + return; + } + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + public void sendFancyMessage(FancyMessage message) { + Player player = getPlayer(); + if (player == null || !player.isOnGround()) { + return; + } + + message.send(player); + } + + public void sendFancyMessage(List messages) { + Player player = getPlayer(); + if (player == null) { + return; + } + + for (FancyMessage msg : messages) { + msg.send(player); + } + } + + public int getMapHeight() { + if (this.mapHeight < 1) { + this.mapHeight = Conf.mapHeight; + } + + return this.mapHeight; + } + + public void setMapHeight(int height) { + this.mapHeight = height > (Conf.mapHeight * 2) ? (Conf.mapHeight * 2) : height; + } + + public String getNameAndTitle(FPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + @Override + public String getChatTag(FPlayer fplayer) { + return this.hasFaction() ? this.getRelationTo(fplayer).getColor() + getChatTag() : ""; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + public abstract void remove(); + + @Override + public void clearWarmup() { + if (warmup != null) { + Bukkit.getScheduler().cancelTask(warmupTask); + this.stopWarmup(); + } + } + + @Override + public void stopWarmup() { + warmup = null; + } + + @Override + public boolean isWarmingUp() { + return warmup != null; + } + + @Override + public WarmUpUtil.Warmup getWarmupType() { + return warmup; + } + + @Override + public void addWarmup(WarmUpUtil.Warmup warmup, int taskId) { + if (this.warmup != null) { + this.clearWarmup(); + } + this.warmup = warmup; + this.warmupTask = taskId; + } + + @Override + public boolean checkIfNearbyEnemies() { + Player me = this.getPlayer(); + + if (me == null) { + return false; + } + + int radius = Conf.stealthFlyCheckRadius; + for (Entity e : me.getNearbyEntities(radius, 255, radius)) { + if (e == null) { + continue; + } + if (e instanceof Player) { + Player eplayer = (((Player) e).getPlayer()); + if (eplayer == null) { + continue; + } + FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); + if (efplayer == null) { + continue; + } + if (efplayer.isVanished()) continue; + if (this.getRelationTo(efplayer).equals(Relation.ENEMY) && !efplayer.isStealthEnabled()) { + setFlying(false); + msg(TL.COMMAND_FLY_ENEMY_NEAR); + Bukkit.getServer().getPluginManager().callEvent(new FPlayerStoppedFlying(this)); + return true; + } + } + } + return false; + } + + @Override + public Boolean canflyinWilderness() { + return getPlayer().hasPermission("factions.fly.wilderness"); + } + + @Override + public Boolean canflyinWarzone() { + return getPlayer().hasPermission("factions.fly.warzone"); + + } + + @Override + public Boolean canflyinSafezone() { + return getPlayer().hasPermission("factions.fly.safezone"); + + } + + @Override + public Boolean canflyinEnemy() { + return getPlayer().hasPermission("factions.fly.enemy"); + + } + + @Override + public Boolean canflyinAlly() { + return getPlayer().hasPermission("factions.fly.ally"); + + } + + @Override + public Boolean canflyinTruce() { + return getPlayer().hasPermission("factions.fly.truce"); + + } + + @Override + public Boolean canflyinNeutral() { + return getPlayer().hasPermission("factions.fly.neutral"); + + } + + @Override + public boolean isInspectMode() { + return inspectMode; + } + + @Override + public void setInspectMode(boolean status) { + inspectMode = status; + } + + public boolean attemptClaim(Faction forFaction, FLocation flocation, boolean notifyFailure) { + // notifyFailure is false if called by auto-claim; no need to notify on every failure for it + // return value is false on failure, true on success + Faction currentFaction = Board.getInstance().getFactionAt(flocation); + int ownedLand = forFaction.getLandRounded(); + + if (!this.canClaimForFactionAtLocation(forFaction, flocation, notifyFailure)) { + return false; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); + double cost = 0.0; + EconomyParticipator payee = null; + if (mustPay) { + cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); + + + if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, forFaction)) { + cost += Conf.econClaimUnconnectedFee; + } + + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) { + payee = this.getFaction(); + } else { + payee = this; + } + + if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { + return false; + } + } + + LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); + Bukkit.getScheduler().runTask(P.p, () -> Bukkit.getPluginManager().callEvent(claimEvent)); + if (claimEvent.isCancelled()) { + return false; + } + + // then make 'em pay (if applicable) + if (mustPay && !Econ.modifyMoney(payee, -cost, TL.CLAIM_TOCLAIM.toString(), TL.CLAIM_FORCLAIM.toString())) { + return false; + } + + // Was an over claim + if (mustPay && currentFaction.isNormal() && currentFaction.hasLandInflation()) { + // Give them money for over claiming. + Econ.modifyMoney(payee, Conf.econOverclaimRewardMultiplier, TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); + } + + // announce success + Set informTheseFPlayers = new HashSet<>(); + informTheseFPlayers.add(this); + informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); + } + + Board.getInstance().setFactionAt(forFaction, flocation); + + if (Conf.logLandClaims) { + P.p.log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); + } + + return true; + } + + + @Override + public String getRolePrefix() { + + switch (getRole()) { + case RECRUIT: + return Conf.prefixRecruit; + case NORMAL: + return Conf.prefixNormal; + case MODERATOR: + return Conf.prefixMod; + case COLEADER: + return Conf.prefixCoLeader; + case LEADER: + return Conf.prefixLeader; + } + + return null; + } + + @Override + public boolean hasMoney(int amt) { + Economy econ = P.p.getEcon(); + if (econ.getBalance(getPlayer()) >= amt) { + return true; + } else { + getPlayer().closeInventory(); + msg(TL.GENERIC_NOTENOUGHMONEY); + return false; + } + } + + public String commas(final double amount) { + final DecimalFormat formatter = new DecimalFormat("#,###.00"); + return formatter.format(amount); + } + + @Override + public void takeMoney(int amt) { + if (hasMoney(amt)) { + Economy econ = P.p.getEcon(); + econ.withdrawPlayer(getPlayer(), amt); + sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", commas(amt))); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java index 9483be35..708baf32 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java @@ -12,55 +12,55 @@ import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; public abstract class MemoryFPlayers extends FPlayers { - public Map fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + public Map fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - public void clean() { - for (FPlayer fplayer : this.fPlayers.values()) { - if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { - P.p.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); - fplayer.resetFactionData(false); - } - } - } + public void clean() { + for (FPlayer fplayer : this.fPlayers.values()) { + if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { + P.p.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); + fplayer.resetFactionData(false); + } + } + } - public Collection getOnlinePlayers() { - Set entities = new HashSet<>(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - entities.add(this.getByPlayer(player)); - } - return entities; - } + public Collection getOnlinePlayers() { + Set entities = new HashSet<>(); + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + entities.add(this.getByPlayer(player)); + } + return entities; + } - @Override - public FPlayer getByPlayer(Player player) { - return getById(player.getUniqueId().toString()); - } + @Override + public FPlayer getByPlayer(Player player) { + return getById(player.getUniqueId().toString()); + } - @Override - public List getAllFPlayers() { - return new ArrayList<>(fPlayers.values()); - } + @Override + public List getAllFPlayers() { + return new ArrayList<>(fPlayers.values()); + } - @Override - public abstract void forceSave(); + @Override + public abstract void forceSave(); - public abstract void load(); + public abstract void load(); - @Override - public FPlayer getByOfflinePlayer(OfflinePlayer player) { - return getById(player.getUniqueId().toString()); - } + @Override + public FPlayer getByOfflinePlayer(OfflinePlayer player) { + return getById(player.getUniqueId().toString()); + } - @Override - public FPlayer getById(String id) { - FPlayer player = fPlayers.get(id); - if (player == null) { - player = generateFPlayer(id); - } - return player; - } + @Override + public FPlayer getById(String id) { + FPlayer player = fPlayers.get(id); + if (player == null) { + player = generateFPlayer(id); + } + return player; + } - public abstract FPlayer generateFPlayer(String id); + public abstract FPlayer generateFPlayer(String id); - public abstract void convertFrom(MemoryFPlayers old); + public abstract void convertFrom(MemoryFPlayers old); } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java index df0a9ebb..1f3b6833 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java @@ -1276,7 +1276,8 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator { public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { // in own faction, with sufficient role or permission to bypass // ownership? - if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.LEADER) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) return true; + if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.LEADER) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) + return true; // make sure claimOwnership is initialized if (claimOwnership.isEmpty()) return true; @@ -1309,5 +1310,7 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator { } } - public Set getAllClaims() { return Board.getInstance().getAllClaims(this); } + public Set getAllClaims() { + return Board.getInstance().getAllClaims(this); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java index 292f083f..76d1caee 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java @@ -13,164 +13,164 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public abstract class MemoryFactions extends Factions { - public final Map factions = new ConcurrentHashMap<>(); - public int nextId = 1; + public final Map factions = new ConcurrentHashMap<>(); + public int nextId = 1; - public void load() { - // Make sure the default neutral faction exists - if (!factions.containsKey("0")) { - Faction faction = generateFactionObject("0"); - factions.put("0", faction); - faction.setTag(TL.WILDERNESS.toString()); - faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("0"); - if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { - faction.setTag(TL.WILDERNESS.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { - faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); - } - } + public void load() { + // Make sure the default neutral faction exists + if (!factions.containsKey("0")) { + Faction faction = generateFactionObject("0"); + factions.put("0", faction); + faction.setTag(TL.WILDERNESS.toString()); + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("0"); + if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { + faction.setTag(TL.WILDERNESS.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } + } - // Make sure the safe zone faction exists - if (!factions.containsKey("-1")) { - Faction faction = generateFactionObject("-1"); - factions.put("-1", faction); - faction.setTag(TL.SAFEZONE.toString()); - faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("-1"); - if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { - faction.setTag(TL.SAFEZONE.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { - faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); - } - // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " - if (faction.getTag().contains(" ")) { - faction.setTag(TL.SAFEZONE.toString()); - } - } + // Make sure the safe zone faction exists + if (!factions.containsKey("-1")) { + Faction faction = generateFactionObject("-1"); + factions.put("-1", faction); + faction.setTag(TL.SAFEZONE.toString()); + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-1"); + if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { + faction.setTag(TL.SAFEZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } + // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.SAFEZONE.toString()); + } + } - // Make sure the war zone faction exists - if (!factions.containsKey("-2")) { - Faction faction = generateFactionObject("-2"); - factions.put("-2", faction); - faction.setTag(TL.WARZONE.toString()); - faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("-2"); - if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { - faction.setTag(TL.WARZONE.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { - faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); - } - // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " - if (faction.getTag().contains(" ")) { - faction.setTag(TL.WARZONE.toString()); - } - } - } + // Make sure the war zone faction exists + if (!factions.containsKey("-2")) { + Faction faction = generateFactionObject("-2"); + factions.put("-2", faction); + faction.setTag(TL.WARZONE.toString()); + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-2"); + if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { + faction.setTag(TL.WARZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } + // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.WARZONE.toString()); + } + } + } - public Faction getFactionById(String id) { - return factions.get(id); - } + public Faction getFactionById(String id) { + return factions.get(id); + } - public abstract Faction generateFactionObject(String string); + public abstract Faction generateFactionObject(String string); - public Faction getByTag(String str) { - String compStr = MiscUtil.getComparisonString(str); - for (Faction faction : factions.values()) { - if (faction.getComparisonTag().equals(compStr)) { - return faction; - } - } - return null; - } + public Faction getByTag(String str) { + String compStr = MiscUtil.getComparisonString(str); + for (Faction faction : factions.values()) { + if (faction.getComparisonTag().equals(compStr)) { + return faction; + } + } + return null; + } - public Faction getBestTagMatch(String start) { - int best = 0; - start = start.toLowerCase(); - int minlength = start.length(); - Faction bestMatch = null; - for (Faction faction : factions.values()) { - String candidate = faction.getTag(); - candidate = ChatColor.stripColor(candidate); - if (candidate.length() < minlength) { - continue; - } - if (!candidate.toLowerCase().startsWith(start)) { - continue; - } + public Faction getBestTagMatch(String start) { + int best = 0; + start = start.toLowerCase(); + int minlength = start.length(); + Faction bestMatch = null; + for (Faction faction : factions.values()) { + String candidate = faction.getTag(); + candidate = ChatColor.stripColor(candidate); + if (candidate.length() < minlength) { + continue; + } + if (!candidate.toLowerCase().startsWith(start)) { + continue; + } - // The closer to zero the better - int lendiff = candidate.length() - minlength; - if (lendiff == 0) { - return faction; - } - if (lendiff < best || best == 0) { - best = lendiff; - bestMatch = faction; - } - } + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return faction; + } + if (lendiff < best || best == 0) { + best = lendiff; + bestMatch = faction; + } + } - return bestMatch; - } + return bestMatch; + } - public boolean isTagTaken(String str) { - return this.getByTag(str) != null; - } + public boolean isTagTaken(String str) { + return this.getByTag(str) != null; + } - public boolean isValidFactionId(String id) { - return factions.containsKey(id); - } + public boolean isValidFactionId(String id) { + return factions.containsKey(id); + } - public Faction createFaction() { - Faction faction = generateFactionObject(); - factions.put(faction.getId(), faction); - return faction; - } + public Faction createFaction() { + Faction faction = generateFactionObject(); + factions.put(faction.getId(), faction); + return faction; + } - public Set getFactionTags() { - Set tags = new HashSet<>(); - for (Faction faction : factions.values()) { - tags.add(faction.getTag()); - } - return tags; - } + public Set getFactionTags() { + Set tags = new HashSet<>(); + for (Faction faction : factions.values()) { + tags.add(faction.getTag()); + } + return tags; + } - public abstract Faction generateFactionObject(); + public abstract Faction generateFactionObject(); - public void removeFaction(String id) { - factions.remove(id).remove(); - } + public void removeFaction(String id) { + factions.remove(id).remove(); + } - @Override - public ArrayList getAllFactions() { - return new ArrayList<>(factions.values()); - } + @Override + public ArrayList getAllFactions() { + return new ArrayList<>(factions.values()); + } - @Override - public Faction getNone() { - return factions.get("0"); - } + @Override + public Faction getNone() { + return factions.get("0"); + } - @Override - public Faction getWilderness() { - return factions.get("0"); - } + @Override + public Faction getWilderness() { + return factions.get("0"); + } - @Override - public Faction getSafeZone() { - return factions.get("-1"); - } + @Override + public Faction getSafeZone() { + return factions.get("-1"); + } - @Override - public Faction getWarZone() { - return factions.get("-2"); - } + @Override + public Faction getWarZone() { + return factions.get("-2"); + } - public abstract void convertFrom(MemoryFactions old); + public abstract void convertFrom(MemoryFactions old); } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java index 892b0853..232c9d21 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java @@ -7,24 +7,24 @@ import com.massivecraft.factions.zcore.MPlugin; public class SaveTask implements Runnable { - private static boolean running = false; + private static boolean running = false; - MPlugin p; + MPlugin p; - public SaveTask(MPlugin p) { - this.p = p; - } + public SaveTask(MPlugin p) { + this.p = p; + } - public void run() { - if (!p.getAutoSave() || running) { - return; - } - running = true; - p.preAutoSave(); - Factions.getInstance().forceSave(false); - FPlayers.getInstance().forceSave(false); - Board.getInstance().forceSave(false); - p.postAutoSave(); - running = false; - } + public void run() { + if (!p.getAutoSave() || running) { + return; + } + running = true; + p.preAutoSave(); + Factions.getInstance().forceSave(false); + FPlayers.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + p.postAutoSave(); + running = false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java index b9d7da42..2cc1c833 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java @@ -10,36 +10,36 @@ import java.util.logging.Logger; public class FactionsJSON { - public static void convertTo() { - if (!(Factions.getInstance() instanceof MemoryFactions)) { - return; - } - if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) { - return; - } - if (!(Board.getInstance() instanceof MemoryBoard)) { - return; - } - new BukkitRunnable() { - @Override - public void run() { - Logger logger = P.p.getLogger(); - logger.info("Beginning Board conversion to JSON"); - new JSONBoard().convertFrom((MemoryBoard) Board.getInstance()); - logger.info("Board Converted"); - logger.info("Beginning FPlayers conversion to JSON"); - new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance()); - logger.info("FPlayers Converted"); - logger.info("Beginning Factions conversion to JSON"); - new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance()); - logger.info("Factions Converted"); - logger.info("Refreshing object caches"); - for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { - Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); - faction.addFPlayer(fPlayer); - } - logger.info("Conversion Complete"); - } - }.runTaskAsynchronously(P.p); - } + public static void convertTo() { + if (!(Factions.getInstance() instanceof MemoryFactions)) { + return; + } + if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) { + return; + } + if (!(Board.getInstance() instanceof MemoryBoard)) { + return; + } + new BukkitRunnable() { + @Override + public void run() { + Logger logger = P.p.getLogger(); + logger.info("Beginning Board conversion to JSON"); + new JSONBoard().convertFrom((MemoryBoard) Board.getInstance()); + logger.info("Board Converted"); + logger.info("Beginning FPlayers conversion to JSON"); + new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance()); + logger.info("FPlayers Converted"); + logger.info("Beginning Factions conversion to JSON"); + new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance()); + logger.info("Factions Converted"); + logger.info("Refreshing object caches"); + for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { + Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); + faction.addFPlayer(fPlayer); + } + logger.info("Conversion Complete"); + } + }.runTaskAsynchronously(P.p); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java index fc15f2ea..53b40aad 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java @@ -16,88 +16,88 @@ import java.util.TreeMap; public class JSONBoard extends MemoryBoard { - private static transient File file = new File(P.p.getDataFolder(), "board.json"); + private static transient File file = new File(P.p.getDataFolder(), "board.json"); - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // - public Map> dumpAsSaveFormat() { - Map> worldCoordIds = new HashMap<>(); + public Map> dumpAsSaveFormat() { + Map> worldCoordIds = new HashMap<>(); - String worldName, coords; - String id; + String worldName, coords; + String id; - for (Entry entry : flocationIds.entrySet()) { - worldName = entry.getKey().getWorldName(); - coords = entry.getKey().getCoordString(); - id = entry.getValue(); - if (!worldCoordIds.containsKey(worldName)) { - worldCoordIds.put(worldName, new TreeMap()); - } + for (Entry entry : flocationIds.entrySet()) { + worldName = entry.getKey().getWorldName(); + coords = entry.getKey().getCoordString(); + id = entry.getValue(); + if (!worldCoordIds.containsKey(worldName)) { + worldCoordIds.put(worldName, new TreeMap()); + } - worldCoordIds.get(worldName).put(coords, id); - } + worldCoordIds.get(worldName).put(coords, id); + } - return worldCoordIds; - } + return worldCoordIds; + } - public void loadFromSaveFormat(Map> worldCoordIds) { - flocationIds.clear(); + public void loadFromSaveFormat(Map> worldCoordIds) { + flocationIds.clear(); - String worldName; - String[] coords; - int x, z; - String factionId; + String worldName; + String[] coords; + int x, z; + String factionId; - for (Entry> entry : worldCoordIds.entrySet()) { - worldName = entry.getKey(); - for (Entry entry2 : entry.getValue().entrySet()) { - coords = entry2.getKey().trim().split("[,\\s]+"); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); - factionId = entry2.getValue(); - flocationIds.put(new FLocation(worldName, x, z), factionId); - } - } - } + for (Entry> entry : worldCoordIds.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + factionId = entry2.getValue(); + flocationIds.put(new FLocation(worldName, x, z), factionId); + } + } + } - public void forceSave() { - forceSave(true); - } + public void forceSave() { + forceSave(true); + } - public void forceSave(boolean sync) { - DiscUtil.writeCatch(file, P.p.gson.toJson(dumpAsSaveFormat()), sync); - } + public void forceSave(boolean sync) { + DiscUtil.writeCatch(file, P.p.gson.toJson(dumpAsSaveFormat()), sync); + } - public boolean load() { - P.p.log("Loading board from disk"); + public boolean load() { + P.p.log("Loading board from disk"); - if (!file.exists()) { - P.p.log("No board to load from disk. Creating new file."); - forceSave(); - return true; - } + if (!file.exists()) { + P.p.log("No board to load from disk. Creating new file."); + forceSave(); + return true; + } - try { - Type type = new TypeToken>>() { - }.getType(); - Map> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); - loadFromSaveFormat(worldCoordIds); - P.p.log("Loaded " + flocationIds.size() + " board locations"); - } catch (Exception e) { - e.printStackTrace(); - P.p.log("Failed to load the board from disk."); - return false; - } + try { + Type type = new TypeToken>>() { + }.getType(); + Map> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); + loadFromSaveFormat(worldCoordIds); + P.p.log("Loaded " + flocationIds.size() + " board locations"); + } catch (Exception e) { + e.printStackTrace(); + P.p.log("Failed to load the board from disk."); + return false; + } - return true; - } + return true; + } - @Override - public void convertFrom(MemoryBoard old) { - this.flocationIds = old.flocationIds; - forceSave(); - Board.instance = this; - } + @Override + public void convertFrom(MemoryBoard old) { + this.flocationIds = old.flocationIds; + forceSave(); + Board.instance = this; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java index d2e0618c..ade236a0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java @@ -6,20 +6,20 @@ import com.massivecraft.factions.zcore.persist.MemoryFPlayer; public class JSONFPlayer extends MemoryFPlayer { - public JSONFPlayer(MemoryFPlayer arg0) { - super(arg0); - } + public JSONFPlayer(MemoryFPlayer arg0) { + super(arg0); + } - public JSONFPlayer(String id) { - super(id); - } + public JSONFPlayer(String id) { + super(id); + } - @Override - public void remove() { - ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); - } + @Override + public void remove() { + ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); + } - public boolean shouldBeSaved() { - return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); - } + public boolean shouldBeSaved() { + return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java index 907c6310..292f01f2 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java @@ -21,170 +21,170 @@ import java.util.Map.Entry; import java.util.logging.Level; public class JSONFPlayers extends MemoryFPlayers { - // Info on how to persist - private Gson gson; - private File file; + // Info on how to persist + private Gson gson; + private File file; - public JSONFPlayers() { - file = new File(P.p.getDataFolder(), "players.json"); - gson = P.p.gson; - } + public JSONFPlayers() { + file = new File(P.p.getDataFolder(), "players.json"); + gson = P.p.gson; + } - public Gson getGson() { - return gson; - } + public Gson getGson() { + return gson; + } - public void setGson(Gson gson) { - this.gson = gson; - } + public void setGson(Gson gson) { + this.gson = gson; + } - public void convertFrom(MemoryFPlayers old) { - this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function() { - @Override - public JSONFPlayer apply(FPlayer arg0) { - return new JSONFPlayer((MemoryFPlayer) arg0); - } - })); - forceSave(); - FPlayers.instance = this; - } + public void convertFrom(MemoryFPlayers old) { + this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function() { + @Override + public JSONFPlayer apply(FPlayer arg0) { + return new JSONFPlayer((MemoryFPlayer) arg0); + } + })); + forceSave(); + FPlayers.instance = this; + } - public void forceSave() { - forceSave(true); - } + public void forceSave() { + forceSave(true); + } - public void forceSave(boolean sync) { - final Map entitiesThatShouldBeSaved = new HashMap<>(); - for (FPlayer entity : this.fPlayers.values()) { - if (((MemoryFPlayer) entity).shouldBeSaved()) { - entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); - } - } + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (FPlayer entity : this.fPlayers.values()) { + if (((MemoryFPlayer) entity).shouldBeSaved()) { + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); + } + } - saveCore(file, entitiesThatShouldBeSaved, sync); - } + saveCore(file, entitiesThatShouldBeSaved, sync); + } - private boolean saveCore(File target, Map data, boolean sync) { - return DiscUtil.writeCatch(target, this.gson.toJson(data), sync); - } + private boolean saveCore(File target, Map data, boolean sync) { + return DiscUtil.writeCatch(target, this.gson.toJson(data), sync); + } - public void load() { - Map fplayers = this.loadCore(); - if (fplayers == null) { - return; - } - this.fPlayers.clear(); - this.fPlayers.putAll(fplayers); - P.p.log("Loaded " + fPlayers.size() + " players"); - } + public void load() { + Map fplayers = this.loadCore(); + if (fplayers == null) { + return; + } + this.fPlayers.clear(); + this.fPlayers.putAll(fplayers); + P.p.log("Loaded " + fPlayers.size() + " players"); + } - private Map loadCore() { - if (!this.file.exists()) { - return new HashMap<>(); - } + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } - String content = DiscUtil.readCatch(this.file); - if (content == null) { - return null; - } + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } - Map data = this.gson.fromJson(content, new TypeToken>() { - }.getType()); - Set list = new HashSet<>(); - Set invalidList = new HashSet<>(); - for (Entry entry : data.entrySet()) { - String key = entry.getKey(); - entry.getValue().setId(key); - if (doesKeyNeedMigration(key)) { - if (!isKeyInvalid(key)) { - list.add(key); - } else { - invalidList.add(key); - } - } - } + Map data = this.gson.fromJson(content, new TypeToken>() { + }.getType()); + Set list = new HashSet<>(); + Set invalidList = new HashSet<>(); + for (Entry entry : data.entrySet()) { + String key = entry.getKey(); + entry.getValue().setId(key); + if (doesKeyNeedMigration(key)) { + if (!isKeyInvalid(key)) { + list.add(key); + } else { + invalidList.add(key); + } + } + } - if (list.size() > 0) { - // We've got some converting to do! - Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); + if (list.size() > 0) { + // We've got some converting to do! + Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); - // First we'll make a backup, because god forbid anybody heed a - // warning - File file = new File(this.file.getParentFile(), "players.json.old"); - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - saveCore(file, data, true); - Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "players.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + saveCore(file, data, true); + Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); - // Start fetching those UUIDs - Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + list.size() + " old player names to UUID. This may take a while."); - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String s : list) { - // Are we missing any responses? - if (!response.containsKey(s)) { - // They don't have a UUID so they should just be removed - invalidList.add(s); - } - } - for (String value : response.keySet()) { - // For all the valid responses, let's replace their old - // named entry with a UUID key - String id = response.get(value).toString(); + // Start fetching those UUIDs + Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + list.size() + " old player names to UUID. This may take a while."); + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String s : list) { + // Are we missing any responses? + if (!response.containsKey(s)) { + // They don't have a UUID so they should just be removed + invalidList.add(s); + } + } + for (String value : response.keySet()) { + // For all the valid responses, let's replace their old + // named entry with a UUID key + String id = response.get(value).toString(); - JSONFPlayer player = data.get(value); + JSONFPlayer player = data.get(value); - if (player == null) { - // The player never existed here, and shouldn't persist - invalidList.add(value); - continue; - } + if (player == null) { + // The player never existed here, and shouldn't persist + invalidList.add(value); + continue; + } - player.setId(id); // Update the object so it knows + player.setId(id); // Update the object so it knows - data.remove(value); // Out with the old... - data.put(id, player); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - if (invalidList.size() > 0) { - for (String name : invalidList) { - // Remove all the invalid names we collected - data.remove(name); - } - Bukkit.getLogger().log(Level.INFO, "While converting we found names that either don't have a UUID or aren't players and removed them from storage."); - Bukkit.getLogger().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", ")); - } - saveCore(this.file, data, true); // Update the - // flatfile - Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); - } - return data; - } + data.remove(value); // Out with the old... + data.put(id, player); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + if (invalidList.size() > 0) { + for (String name : invalidList) { + // Remove all the invalid names we collected + data.remove(name); + } + Bukkit.getLogger().log(Level.INFO, "While converting we found names that either don't have a UUID or aren't players and removed them from storage."); + Bukkit.getLogger().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", ")); + } + saveCore(this.file, data, true); // Update the + // flatfile + Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); + } + return data; + } - private boolean doesKeyNeedMigration(String key) { - if (!key.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { - // Not a valid UUID.. - // Valid playername, we'll mark this as one for conversion - // to UUID - return key.matches("[a-zA-Z0-9_]{2,16}"); - } - return false; - } + private boolean doesKeyNeedMigration(String key) { + if (!key.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + // Valid playername, we'll mark this as one for conversion + // to UUID + return key.matches("[a-zA-Z0-9_]{2,16}"); + } + return false; + } - private boolean isKeyInvalid(String key) { - return !key.matches("[a-zA-Z0-9_]{2,16}"); - } + private boolean isKeyInvalid(String key) { + return !key.matches("[a-zA-Z0-9_]{2,16}"); + } - @Override - public FPlayer generateFPlayer(String id) { - FPlayer player = new JSONFPlayer(id); - this.fPlayers.put(player.getId(), player); - return player; - } + @Override + public FPlayer generateFPlayer(String id) { + FPlayer player = new JSONFPlayer(id); + this.fPlayers.put(player.getId(), player); + return player; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java index 6068cde9..c5805ba0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java @@ -4,15 +4,15 @@ import com.massivecraft.factions.zcore.persist.MemoryFaction; public class JSONFaction extends MemoryFaction { - public JSONFaction(MemoryFaction arg0) { - super(arg0); - } + public JSONFaction(MemoryFaction arg0) { + super(arg0); + } - public JSONFaction() { - } + public JSONFaction() { + } - public JSONFaction(String id) { - super(id); - } + public JSONFaction(String id) { + super(id); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java index 4599ce35..8cdd06c3 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java @@ -21,233 +21,233 @@ import java.util.Map.Entry; import java.util.logging.Level; public class JSONFactions extends MemoryFactions { - // Info on how to persist - private final Gson gson; - private final File file; + // Info on how to persist + private final Gson gson; + private final File file; - public JSONFactions() { - this.file = new File(P.p.getDataFolder(), "factions.json"); - this.gson = P.p.gson; - this.nextId = 1; - } + public JSONFactions() { + this.file = new File(P.p.getDataFolder(), "factions.json"); + this.gson = P.p.gson; + this.nextId = 1; + } - public Gson getGson() { - return gson; - } + public Gson getGson() { + return gson; + } - // -------------------------------------------- // - // CONSTRUCTORS - // -------------------------------------------- // + // -------------------------------------------- // + // CONSTRUCTORS + // -------------------------------------------- // - public File getFile() { - return file; - } + public File getFile() { + return file; + } - public void forceSave() { - forceSave(true); - } + public void forceSave() { + forceSave(true); + } - public void forceSave(boolean sync) { - final Map entitiesThatShouldBeSaved = new HashMap<>(); - for (Faction entity : this.factions.values()) { - entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); - } + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (Faction entity : this.factions.values()) { + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); + } - saveCore(file, entitiesThatShouldBeSaved, sync); - } + saveCore(file, entitiesThatShouldBeSaved, sync); + } - private boolean saveCore(File target, Map entities, boolean sync) { - return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync); - } + private boolean saveCore(File target, Map entities, boolean sync) { + return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync); + } - public void load() { - Map factions = this.loadCore(); - if (factions == null) { - return; - } - this.factions.putAll(factions); + public void load() { + Map factions = this.loadCore(); + if (factions == null) { + return; + } + this.factions.putAll(factions); - super.load(); - P.p.log("Loaded " + factions.size() + " Factions"); - } + super.load(); + P.p.log("Loaded " + factions.size() + " Factions"); + } - private Map loadCore() { - if (!this.file.exists()) { - return new HashMap<>(); - } + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } - String content = DiscUtil.readCatch(this.file); - if (content == null) { - return null; - } + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } - Map data = this.gson.fromJson(content, new TypeToken>() { - }.getType()); + Map data = this.gson.fromJson(content, new TypeToken>() { + }.getType()); - this.nextId = 1; - // Do we have any names that need updating in claims or invites? + this.nextId = 1; + // Do we have any names that need updating in claims or invites? - int needsUpdate = 0; - for (Entry entry : data.entrySet()) { - String id = entry.getKey(); - Faction f = entry.getValue(); - f.setId(id); - this.updateNextIdForId(id); - needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); - for (Set keys : f.getClaimOwnership().values()) { - needsUpdate += whichKeysNeedMigration(keys).size(); - } - } + int needsUpdate = 0; + for (Entry entry : data.entrySet()) { + String id = entry.getKey(); + Faction f = entry.getValue(); + f.setId(id); + this.updateNextIdForId(id); + needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); + for (Set keys : f.getClaimOwnership().values()) { + needsUpdate += whichKeysNeedMigration(keys).size(); + } + } - if (needsUpdate > 0) { - // We've got some converting to do! - Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json"); + if (needsUpdate > 0) { + // We've got some converting to do! + Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json"); - // First we'll make a backup, because god forbid anybody heed a - // warning - File file = new File(this.file.getParentFile(), "factions.json.old"); - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - saveCore(file, data, true); - Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "factions.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + saveCore(file, data, true); + Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); - Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); + Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); - // Update claim ownership + // Update claim ownership - for (String string : data.keySet()) { - Faction f = data.get(string); - Map> claims = f.getClaimOwnership(); - for (FLocation key : claims.keySet()) { - Set set = claims.get(key); + for (String string : data.keySet()) { + Faction f = data.get(string); + Map> claims = f.getClaimOwnership(); + for (FLocation key : claims.keySet()) { + Set set = claims.get(key); - Set list = whichKeysNeedMigration(set); + Set list = whichKeysNeedMigration(set); - if (list.size() > 0) { - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String value : response.keySet()) { - // Let's replace their old named entry with a - // UUID key - String id = response.get(value).toString(); - set.remove(value.toLowerCase()); // Out with the - // old... - set.add(id); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - claims.put(key, set); // Update - } - } - } + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a + // UUID key + String id = response.get(value).toString(); + set.remove(value.toLowerCase()); // Out with the + // old... + set.add(id); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + claims.put(key, set); // Update + } + } + } - // Update invites + // Update invites - for (String string : data.keySet()) { - Faction f = data.get(string); - Set invites = f.getInvites(); - Set list = whichKeysNeedMigration(invites); + for (String string : data.keySet()) { + Faction f = data.get(string); + Set invites = f.getInvites(); + Set list = whichKeysNeedMigration(invites); - if (list.size() > 0) { - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String value : response.keySet()) { - // Let's replace their old named entry with a UUID - // key - String id = response.get(value).toString(); - invites.remove(value.toLowerCase()); // Out with the - // old... - invites.add(id); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a UUID + // key + String id = response.get(value).toString(); + invites.remove(value.toLowerCase()); // Out with the + // old... + invites.add(id); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } - saveCore(this.file, data, true); // Update the flatfile - Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); - } - return data; - } + saveCore(this.file, data, true); // Update the flatfile + Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); + } + return data; + } - private Set whichKeysNeedMigration(Set keys) { - HashSet list = new HashSet<>(); - for (String value : keys) { - if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { - // Not a valid UUID.. - if (value.matches("[a-zA-Z0-9_]{2,16}")) { - // Valid playername, we'll mark this as one for conversion - // to UUID - list.add(value); - } - } - } - return list; - } + private Set whichKeysNeedMigration(Set keys) { + HashSet list = new HashSet<>(); + for (String value : keys) { + if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + if (value.matches("[a-zA-Z0-9_]{2,16}")) { + // Valid playername, we'll mark this as one for conversion + // to UUID + list.add(value); + } + } + } + return list; + } - // -------------------------------------------- // - // ID MANAGEMENT - // -------------------------------------------- // + // -------------------------------------------- // + // ID MANAGEMENT + // -------------------------------------------- // - public String getNextId() { - while (!isIdFree(this.nextId)) { - this.nextId += 1; - } - return Integer.toString(this.nextId); - } + public String getNextId() { + while (!isIdFree(this.nextId)) { + this.nextId += 1; + } + return Integer.toString(this.nextId); + } - public boolean isIdFree(String id) { - return !this.factions.containsKey(id); - } + public boolean isIdFree(String id) { + return !this.factions.containsKey(id); + } - public boolean isIdFree(int id) { - return this.isIdFree(Integer.toString(id)); - } + public boolean isIdFree(int id) { + return this.isIdFree(Integer.toString(id)); + } - protected synchronized void updateNextIdForId(int id) { - if (this.nextId < id) { - this.nextId = id + 1; - } - } + protected synchronized void updateNextIdForId(int id) { + if (this.nextId < id) { + this.nextId = id + 1; + } + } - protected void updateNextIdForId(String id) { - try { - int idAsInt = Integer.parseInt(id); - this.updateNextIdForId(idAsInt); - } catch (Exception ignored) { - } - } + protected void updateNextIdForId(String id) { + try { + int idAsInt = Integer.parseInt(id); + this.updateNextIdForId(idAsInt); + } catch (Exception ignored) { + } + } - @Override - public Faction generateFactionObject() { - String id = getNextId(); - Faction faction = new JSONFaction(id); - updateNextIdForId(id); - return faction; - } + @Override + public Faction generateFactionObject() { + String id = getNextId(); + Faction faction = new JSONFaction(id); + updateNextIdForId(id); + return faction; + } - @Override - public Faction generateFactionObject(String id) { - return new JSONFaction(id); - } + @Override + public Faction generateFactionObject(String id) { + return new JSONFaction(id); + } - @Override - public void convertFrom(MemoryFactions old) { - this.factions.putAll(Maps.transformValues(old.factions, new Function() { - @Override - public JSONFaction apply(Faction arg0) { - return new JSONFaction((MemoryFaction) arg0); - } - })); - this.nextId = old.nextId; - forceSave(); - Factions.instance = this; - } + @Override + public void convertFrom(MemoryFactions old) { + this.factions.putAll(Maps.transformValues(old.factions, new Function() { + @Override + public JSONFaction apply(Faction arg0) { + return new JSONFaction((MemoryFaction) arg0); + } + })); + this.nextId = old.nextId; + forceSave(); + Factions.instance = this; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java index 25db32a2..9485f166 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java @@ -12,107 +12,107 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; public class DiscUtil { - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // - private final static String UTF8 = "UTF-8"; + private final static String UTF8 = "UTF-8"; - // -------------------------------------------- // - // BYTE - // -------------------------------------------- // - private static HashMap locks = new HashMap<>(); + // -------------------------------------------- // + // BYTE + // -------------------------------------------- // + private static HashMap locks = new HashMap<>(); - public static byte[] readBytes(File file) throws IOException { - int length = (int) file.length(); - byte[] output = new byte[length]; - InputStream in = new FileInputStream(file); - int offset = 0; - while (offset < length) { - offset += in.read(output, offset, (length - offset)); - } - in.close(); - return output; - } + public static byte[] readBytes(File file) throws IOException { + int length = (int) file.length(); + byte[] output = new byte[length]; + InputStream in = new FileInputStream(file); + int offset = 0; + while (offset < length) { + offset += in.read(output, offset, (length - offset)); + } + in.close(); + return output; + } - // -------------------------------------------- // - // STRING - // -------------------------------------------- // + // -------------------------------------------- // + // STRING + // -------------------------------------------- // - public static void writeBytes(File file, byte[] bytes) throws IOException { - FileOutputStream out = new FileOutputStream(file); - out.write(bytes); - out.close(); - } + public static void writeBytes(File file, byte[] bytes) throws IOException { + FileOutputStream out = new FileOutputStream(file); + out.write(bytes); + out.close(); + } - public static void write(File file, String content) throws IOException { - writeBytes(file, utf8(content)); - } + public static void write(File file, String content) throws IOException { + writeBytes(file, utf8(content)); + } - // -------------------------------------------- // - // CATCH - // -------------------------------------------- // + // -------------------------------------------- // + // CATCH + // -------------------------------------------- // - public static String read(File file) throws IOException { - return utf8(readBytes(file)); - } + public static String read(File file) throws IOException { + return utf8(readBytes(file)); + } - public static boolean writeCatch(final File file, final String content, boolean sync) { - String name = file.getName(); - final Lock lock; + public static boolean writeCatch(final File file, final String content, boolean sync) { + String name = file.getName(); + final Lock lock; - // Create lock for each file if there isn't already one. - if (locks.containsKey(name)) { - lock = locks.get(name); - } else { - ReadWriteLock rwl = new ReentrantReadWriteLock(); - lock = rwl.writeLock(); - locks.put(name, lock); - } + // Create lock for each file if there isn't already one. + if (locks.containsKey(name)) { + lock = locks.get(name); + } else { + ReadWriteLock rwl = new ReentrantReadWriteLock(); + lock = rwl.writeLock(); + locks.put(name, lock); + } - if (sync) { - lock.lock(); - try { - write(file, content); - } catch (IOException e) { - e.printStackTrace(); - } finally { - lock.unlock(); - } - } else { - Bukkit.getScheduler().runTaskAsynchronously(P.p, () -> { - lock.lock(); - try { - write(file, content); - } catch (IOException e) { - e.printStackTrace(); - } finally { - lock.unlock(); - } - }); - } + if (sync) { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + e.printStackTrace(); + } finally { + lock.unlock(); + } + } else { + Bukkit.getScheduler().runTaskAsynchronously(P.p, () -> { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + e.printStackTrace(); + } finally { + lock.unlock(); + } + }); + } - return true; // don't really care but for some reason this is a boolean. - } + return true; // don't really care but for some reason this is a boolean. + } - public static String readCatch(File file) { - try { - return read(file); - } catch (IOException e) { - return null; - } - } + public static String readCatch(File file) { + try { + return read(file); + } catch (IOException e) { + return null; + } + } - // -------------------------------------------- // - // UTF8 ENCODE AND DECODE - // -------------------------------------------- // + // -------------------------------------------- // + // UTF8 ENCODE AND DECODE + // -------------------------------------------- // - public static byte[] utf8(String string) { - return string.getBytes(StandardCharsets.UTF_8); - } + public static byte[] utf8(String string) { + return string.getBytes(StandardCharsets.UTF_8); + } - public static String utf8(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } + public static String utf8(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java index 5d457631..3d8a8933 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java @@ -10,65 +10,65 @@ import java.util.Map.Entry; public class PermUtil { - public Map permissionDescriptions = new HashMap<>(); + public Map permissionDescriptions = new HashMap<>(); - protected MPlugin p; + protected MPlugin p; - public PermUtil(MPlugin p) { - this.p = p; - this.setup(); - } + public PermUtil(MPlugin p) { + this.p = p; + this.setup(); + } - public String getForbiddenMessage(String perm) { - return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); - } + public String getForbiddenMessage(String perm) { + return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); + } - /** - * This method hooks into all permission plugins we are supporting - */ - public final void setup() { - for (Permission permission : p.getDescription().getPermissions()) { - //plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); - this.permissionDescriptions.put(permission.getName(), permission.getDescription()); - } - } + /** + * This method hooks into all permission plugins we are supporting + */ + public final void setup() { + for (Permission permission : p.getDescription().getPermissions()) { + //plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); + this.permissionDescriptions.put(permission.getName(), permission.getDescription()); + } + } - public String getPermissionDescription(String perm) { - String desc = permissionDescriptions.get(perm); + public String getPermissionDescription(String perm) { + String desc = permissionDescriptions.get(perm); - return desc != null ? desc : TL.GENERIC_DOTHAT.toString(); - } + return desc != null ? desc : TL.GENERIC_DOTHAT.toString(); + } - /** - * This method tests if me has a certain permission and returns true if me has. Otherwise false - */ - public boolean has(CommandSender me, String perm) { - return me != null && me.hasPermission(perm); - } + /** + * This method tests if me has a certain permission and returns true if me has. Otherwise false + */ + public boolean has(CommandSender me, String perm) { + return me != null && me.hasPermission(perm); + } - public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { - if (has(me, perm)) { - return true; - } else if (informSenderIfNot && me != null) { - me.sendMessage(this.getForbiddenMessage(perm)); - } - return false; - } + public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { + if (has(me, perm)) { + return true; + } else if (informSenderIfNot && me != null) { + me.sendMessage(this.getForbiddenMessage(perm)); + } + return false; + } - public T pickFirstVal(CommandSender me, Map perm2val) { - if (perm2val == null) { - return null; - } - T ret = null; + public T pickFirstVal(CommandSender me, Map perm2val) { + if (perm2val == null) { + return null; + } + T ret = null; - for (Entry entry : perm2val.entrySet()) { - ret = entry.getValue(); - if (has(me, entry.getKey())) { - break; - } - } + for (Entry entry : perm2val.entrySet()) { + ret = entry.getValue(); + if (has(me, entry.getKey())) { + break; + } + } - return ret; - } + return ret; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java index d7f038d0..7b637b47 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java @@ -10,144 +10,144 @@ import java.util.logging.Level; public class Persist { - private MPlugin p; + private MPlugin p; - public Persist(MPlugin p) { - this.p = p; - } + public Persist(MPlugin p) { + this.p = p; + } - // ------------------------------------------------------------ // - // GET NAME - What should we call this type of object? - // ------------------------------------------------------------ // + // ------------------------------------------------------------ // + // GET NAME - What should we call this type of object? + // ------------------------------------------------------------ // - public static String getName(Class clazz) { - return clazz.getSimpleName().toLowerCase(); - } + public static String getName(Class clazz) { + return clazz.getSimpleName().toLowerCase(); + } - public static String getName(Object o) { - return getName(o.getClass()); - } + public static String getName(Object o) { + return getName(o.getClass()); + } - public static String getName(Type type) { - return getName(type.getClass()); - } + public static String getName(Type type) { + return getName(type.getClass()); + } - // ------------------------------------------------------------ // - // GET FILE - In which file would we like to store this object? - // ------------------------------------------------------------ // + // ------------------------------------------------------------ // + // GET FILE - In which file would we like to store this object? + // ------------------------------------------------------------ // - public File getFile(String name) { - return new File(p.getDataFolder(), name + ".json"); - } + public File getFile(String name) { + return new File(p.getDataFolder(), name + ".json"); + } - public File getFile(Class clazz) { - return getFile(getName(clazz)); - } + public File getFile(Class clazz) { + return getFile(getName(clazz)); + } - public File getFile(Object obj) { - return getFile(getName(obj)); - } + public File getFile(Object obj) { + return getFile(getName(obj)); + } - public File getFile(Type type) { - return getFile(getName(type)); - } + public File getFile(Type type) { + return getFile(getName(type)); + } - // NICE WRAPPERS + // NICE WRAPPERS - public T loadOrSaveDefault(T def, Class clazz) { - return loadOrSaveDefault(def, clazz, getFile(clazz)); - } + public T loadOrSaveDefault(T def, Class clazz) { + return loadOrSaveDefault(def, clazz, getFile(clazz)); + } - public T loadOrSaveDefault(T def, Class clazz, String name) { - return loadOrSaveDefault(def, clazz, getFile(name)); - } + public T loadOrSaveDefault(T def, Class clazz, String name) { + return loadOrSaveDefault(def, clazz, getFile(name)); + } - public T loadOrSaveDefault(T def, Class clazz, File file) { - if (!file.exists()) { - p.log("Creating default: " + file); - this.save(def, file); - return def; - } + public T loadOrSaveDefault(T def, Class clazz, File file) { + if (!file.exists()) { + p.log("Creating default: " + file); + this.save(def, file); + return def; + } - T loaded = this.load(clazz, file); + T loaded = this.load(clazz, file); - if (loaded == null) { - p.log(Level.WARNING, "Using default as I failed to load: " + file); + if (loaded == null) { + p.log(Level.WARNING, "Using default as I failed to load: " + file); - // backup bad file, so user can attempt to recover their changes from it - File backup = new File(file.getPath() + "_bad"); - if (backup.exists()) { - backup.delete(); - } - p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); - file.renameTo(backup); + // backup bad file, so user can attempt to recover their changes from it + File backup = new File(file.getPath() + "_bad"); + if (backup.exists()) { + backup.delete(); + } + p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); + file.renameTo(backup); - return def; - } + return def; + } - return loaded; - } + return loaded; + } - // SAVE + // SAVE - public boolean save(Object instance) { - return save(instance, getFile(instance)); - } + public boolean save(Object instance) { + return save(instance, getFile(instance)); + } - public boolean save(Object instance, String name) { - return save(instance, getFile(name)); - } + public boolean save(Object instance, String name) { + return save(instance, getFile(name)); + } - public boolean save(Object instance, File file) { - return DiscUtil.writeCatch(file, p.gson.toJson(instance), false); - } + public boolean save(Object instance, File file) { + return DiscUtil.writeCatch(file, p.gson.toJson(instance), false); + } - // LOAD BY CLASS + // LOAD BY CLASS - public T load(Class clazz) { - return load(clazz, getFile(clazz)); - } + public T load(Class clazz) { + return load(clazz, getFile(clazz)); + } - public T load(Class clazz, String name) { - return load(clazz, getFile(name)); - } + public T load(Class clazz, String name) { + return load(clazz, getFile(name)); + } - public T load(Class clazz, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { - return null; - } + public T load(Class clazz, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } - try { - return p.gson.fromJson(content, clazz); - } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + try { + return p.gson.fromJson(content, clazz); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } - return null; - } + return null; + } - // LOAD BY TYPE - @SuppressWarnings("unchecked") - public T load(Type typeOfT, String name) { - return (T) load(typeOfT, getFile(name)); - } + // LOAD BY TYPE + @SuppressWarnings("unchecked") + public T load(Type typeOfT, String name) { + return (T) load(typeOfT, getFile(name)); + } - @SuppressWarnings("unchecked") - public T load(Type typeOfT, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { - return null; - } + @SuppressWarnings("unchecked") + public T load(Type typeOfT, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } - try { - return (T) p.gson.fromJson(content, typeOfT); - } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + try { + return (T) p.gson.fromJson(content, typeOfT); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } - return null; - } + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java index cacba74b..6451a699 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java @@ -24,59 +24,59 @@ import java.util.Random; public class SmokeUtil { - public static Random random = new Random(); + public static Random random = new Random(); - // -------------------------------------------- // - // Spawn once - // -------------------------------------------- // + // -------------------------------------------- // + // Spawn once + // -------------------------------------------- // - // Single ======== - public static void spawnSingle(Location location, int direction) { - if (location == null) { - return; - } - location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); - } + // Single ======== + public static void spawnSingle(Location location, int direction) { + if (location == null) { + return; + } + location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); + } - public static void spawnSingle(Location location) { - spawnSingle(location, 4); - } + public static void spawnSingle(Location location) { + spawnSingle(location, 4); + } - public static void spawnSingleRandom(Location location) { - spawnSingle(location, random.nextInt(9)); - } + public static void spawnSingleRandom(Location location) { + spawnSingle(location, random.nextInt(9)); + } - // Simple Cloud ======== - public static void spawnCloudSimple(Location location) { - for (int i = 0; i <= 8; i++) { - spawnSingle(location, i); - } - } + // Simple Cloud ======== + public static void spawnCloudSimple(Location location) { + for (int i = 0; i <= 8; i++) { + spawnSingle(location, i); + } + } - public static void spawnCloudSimple(Collection locations) { - for (Location location : locations) { - spawnCloudSimple(location); - } - } + public static void spawnCloudSimple(Collection locations) { + for (Location location : locations) { + spawnCloudSimple(location); + } + } - // Random Cloud ======== - public static void spawnCloudRandom(Location location, float thickness) { - int singles = (int) Math.floor(thickness * 9); - for (int i = 0; i < singles; i++) { - spawnSingleRandom(location.clone()); - } - } + // Random Cloud ======== + public static void spawnCloudRandom(Location location, float thickness) { + int singles = (int) Math.floor(thickness * 9); + for (int i = 0; i < singles; i++) { + spawnSingleRandom(location.clone()); + } + } - public static void spawnCloudRandom(Collection locations, float thickness) { - for (Location location : locations) { - spawnCloudRandom(location, thickness); - } - } + public static void spawnCloudRandom(Collection locations, float thickness) { + for (Location location : locations) { + spawnCloudRandom(location, thickness); + } + } - // -------------------------------------------- // - // Attach continuous effects to or locations - // -------------------------------------------- // + // -------------------------------------------- // + // Attach continuous effects to or locations + // -------------------------------------------- // - // TODO + // TODO } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java index e91b129e..24ff4c19 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java @@ -17,293 +17,293 @@ import java.util.UUID; */ public enum TagReplacer { - /** - * Fancy variables, used by f show - */ - ALLIES_LIST(TagType.FANCY, "{allies-list}"), - ONLINE_LIST(TagType.FANCY, "{online-list}"), - ENEMIES_LIST(TagType.FANCY, "{enemies-list}"), - TRUCES_LIST(TagType.FANCY, "{truces-list}"), - OFFLINE_LIST(TagType.FANCY, "{offline-list}"), - ALTS(TagType.FANCY, "{alts}"), + /** + * Fancy variables, used by f show + */ + ALLIES_LIST(TagType.FANCY, "{allies-list}"), + ONLINE_LIST(TagType.FANCY, "{online-list}"), + ENEMIES_LIST(TagType.FANCY, "{enemies-list}"), + TRUCES_LIST(TagType.FANCY, "{truces-list}"), + OFFLINE_LIST(TagType.FANCY, "{offline-list}"), + ALTS(TagType.FANCY, "{alts}"), - /** - * Player variables, require a player - */ - PLAYER_GROUP(TagType.PLAYER, "{group}"), - LAST_SEEN(TagType.PLAYER, "{lastSeen}"), - PLAYER_BALANCE(TagType.PLAYER, "{balance}"), - PLAYER_POWER(TagType.PLAYER, "{player-power}"), - PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"), - PLAYER_KILLS(TagType.PLAYER, "{player-kills}"), - PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"), + /** + * Player variables, require a player + */ + PLAYER_GROUP(TagType.PLAYER, "{group}"), + LAST_SEEN(TagType.PLAYER, "{lastSeen}"), + PLAYER_BALANCE(TagType.PLAYER, "{balance}"), + PLAYER_POWER(TagType.PLAYER, "{player-power}"), + PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"), + PLAYER_KILLS(TagType.PLAYER, "{player-kills}"), + PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"), - /** - * Faction variables, require at least a player - */ - HOME_X(TagType.FACTION, "{x}"), - HOME_Y(TagType.FACTION, "{y}"), - HOME_Z(TagType.FACTION, "{z}"), - CHUNKS(TagType.FACTION, "{chunks}"), - WARPS(TagType.FACTION, "{warps}"), - HEADER(TagType.FACTION, "{header}"), - POWER(TagType.FACTION, "{power}"), - MAX_POWER(TagType.FACTION, "{maxPower}"), - POWER_BOOST(TagType.FACTION, "{power-boost}"), - LEADER(TagType.FACTION, "{leader}"), - JOINING(TagType.FACTION, "{joining}"), - FACTION(TagType.FACTION, "{faction}"), - PLAYER_NAME(TagType.FACTION, "{name}"), - HOME_WORLD(TagType.FACTION, "{world}"), - RAIDABLE(TagType.FACTION, "{raidable}"), - PEACEFUL(TagType.FACTION, "{peaceful}"), - PERMANENT(TagType.FACTION, "permanent"), // no braces needed - TIME_LEFT(TagType.FACTION, "{time-left}"), - LAND_VALUE(TagType.FACTION, "{land-value}"), - DESCRIPTION(TagType.FACTION, "{description}"), - CREATE_DATE(TagType.FACTION, "{create-date}"), - LAND_REFUND(TagType.FACTION, "{land-refund}"), - BANK_BALANCE(TagType.FACTION, "{faction-balance}"), - ALLIES_COUNT(TagType.FACTION, "{allies}"), - ENEMIES_COUNT(TagType.FACTION, "{enemies}"), - TRUCES_COUNT(TagType.FACTION, "{truces}"), - ONLINE_COUNT(TagType.FACTION, "{online}"), - OFFLINE_COUNT(TagType.FACTION, "{offline}"), - FACTION_SIZE(TagType.FACTION, "{members}"), - FACTION_KILLS(TagType.FACTION, "{faction-kills}"), - FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"), - FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"), - FACTION_STRIKES(TagType.FACTION, "{strikes}"), - FACTION_POINTS(TagType.FACTION, "{faction-points}"), + /** + * Faction variables, require at least a player + */ + HOME_X(TagType.FACTION, "{x}"), + HOME_Y(TagType.FACTION, "{y}"), + HOME_Z(TagType.FACTION, "{z}"), + CHUNKS(TagType.FACTION, "{chunks}"), + WARPS(TagType.FACTION, "{warps}"), + HEADER(TagType.FACTION, "{header}"), + POWER(TagType.FACTION, "{power}"), + MAX_POWER(TagType.FACTION, "{maxPower}"), + POWER_BOOST(TagType.FACTION, "{power-boost}"), + LEADER(TagType.FACTION, "{leader}"), + JOINING(TagType.FACTION, "{joining}"), + FACTION(TagType.FACTION, "{faction}"), + PLAYER_NAME(TagType.FACTION, "{name}"), + HOME_WORLD(TagType.FACTION, "{world}"), + RAIDABLE(TagType.FACTION, "{raidable}"), + PEACEFUL(TagType.FACTION, "{peaceful}"), + PERMANENT(TagType.FACTION, "permanent"), // no braces needed + TIME_LEFT(TagType.FACTION, "{time-left}"), + LAND_VALUE(TagType.FACTION, "{land-value}"), + DESCRIPTION(TagType.FACTION, "{description}"), + CREATE_DATE(TagType.FACTION, "{create-date}"), + LAND_REFUND(TagType.FACTION, "{land-refund}"), + BANK_BALANCE(TagType.FACTION, "{faction-balance}"), + ALLIES_COUNT(TagType.FACTION, "{allies}"), + ENEMIES_COUNT(TagType.FACTION, "{enemies}"), + TRUCES_COUNT(TagType.FACTION, "{truces}"), + ONLINE_COUNT(TagType.FACTION, "{online}"), + OFFLINE_COUNT(TagType.FACTION, "{offline}"), + FACTION_SIZE(TagType.FACTION, "{members}"), + FACTION_KILLS(TagType.FACTION, "{faction-kills}"), + FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"), + FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"), + FACTION_STRIKES(TagType.FACTION, "{strikes}"), + FACTION_POINTS(TagType.FACTION, "{faction-points}"), - /** - * General variables, require no faction or player - */ - MAX_WARPS(TagType.GENERAL, "{max-warps}"), - MAX_ALLIES(TagType.GENERAL, "{max-allies}"), - MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"), - MAX_TRUCES(TagType.GENERAL, "{max-truces}"), - FACTIONLESS(TagType.GENERAL, "{factionless}"), - TOTAL_ONLINE(TagType.GENERAL, "{total-online}"); + /** + * General variables, require no faction or player + */ + MAX_WARPS(TagType.GENERAL, "{max-warps}"), + MAX_ALLIES(TagType.GENERAL, "{max-allies}"), + MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"), + MAX_TRUCES(TagType.GENERAL, "{max-truces}"), + FACTIONLESS(TagType.GENERAL, "{factionless}"), + TOTAL_ONLINE(TagType.GENERAL, "{total-online}"); - private TagType type; - private String tag; + private TagType type; + private String tag; - TagReplacer(TagType type, String tag) { - this.type = type; - this.tag = tag; - } + TagReplacer(TagType type, String tag) { + this.type = type; + this.tag = tag; + } - /** - * Returns a list of all the variables we can use for this type
- * - * @param type the type we want - * @return a list of all the variables with this type - */ - protected static List getByType(TagType type) { - List tagReplacers = new ArrayList<>(); - for (TagReplacer tagReplacer : TagReplacer.values()) { - if (type == TagType.FANCY) { - if (tagReplacer.type == TagType.FANCY) { - tagReplacers.add(tagReplacer); - } - } else if (tagReplacer.type.id >= type.id) { - tagReplacers.add(tagReplacer); - } - } - return tagReplacers; - } + /** + * Returns a list of all the variables we can use for this type
+ * + * @param type the type we want + * @return a list of all the variables with this type + */ + protected static List getByType(TagType type) { + List tagReplacers = new ArrayList<>(); + for (TagReplacer tagReplacer : TagReplacer.values()) { + if (type == TagType.FANCY) { + if (tagReplacer.type == TagType.FANCY) { + tagReplacers.add(tagReplacer); + } + } else if (tagReplacer.type.id >= type.id) { + tagReplacers.add(tagReplacer); + } + } + return tagReplacers; + } - /** - * Protected access to this generic server related variable - * - * @return value for this generic server related variable
- */ - protected String getValue() { - switch (this) { - case TOTAL_ONLINE: - return String.valueOf(Bukkit.getOnlinePlayers().size()); - case FACTIONLESS: - return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size()); - case MAX_ALLIES: - if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(P.p.getConfig().getInt("max-relations.ally", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_ENEMIES: - if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(P.p.getConfig().getInt("max-relations.enemy", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_TRUCES: - if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(P.p.getConfig().getInt("max-relations.truce", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_WARPS: - return String.valueOf(P.p.getConfig().getInt("max-warps", 5)); - default: - } - return null; - } + /** + * Protected access to this generic server related variable + * + * @return value for this generic server related variable
+ */ + protected String getValue() { + switch (this) { + case TOTAL_ONLINE: + return String.valueOf(Bukkit.getOnlinePlayers().size()); + case FACTIONLESS: + return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size()); + case MAX_ALLIES: + if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(P.p.getConfig().getInt("max-relations.ally", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_ENEMIES: + if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(P.p.getConfig().getInt("max-relations.enemy", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_TRUCES: + if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(P.p.getConfig().getInt("max-relations.truce", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_WARPS: + return String.valueOf(P.p.getConfig().getInt("max-warps", 5)); + default: + } + return null; + } - /** - * Gets the value for this (as in the instance this is called from) variable! - * - * @param fac Target faction - * @param fp Target player (can be null) - * @return the value for this enum! - */ - protected String getValue(Faction fac, FPlayer fp) { - if (this.type == TagType.GENERAL) { - return getValue(); - } + /** + * Gets the value for this (as in the instance this is called from) variable! + * + * @param fac Target faction + * @param fp Target player (can be null) + * @return the value for this enum! + */ + protected String getValue(Faction fac, FPlayer fp) { + if (this.type == TagType.GENERAL) { + return getValue(); + } - boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); + boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); - if (fp != null) { - switch (this) { - case HEADER: - return P.p.txt.titleize(fac.getTag(fp)); - case PLAYER_NAME: - return fp.getName(); - case FACTION: - return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString(); - case LAST_SEEN: - String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; - return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); - case PLAYER_GROUP: - return P.p.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); - case PLAYER_BALANCE: - return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); - case PLAYER_POWER: - return String.valueOf(fp.getPowerRounded()); - case PLAYER_MAXPOWER: - return String.valueOf(fp.getPowerMaxRounded()); - case PLAYER_KILLS: - return String.valueOf(fp.getKills()); - case PLAYER_DEATHS: - return String.valueOf(fp.getDeaths()); - default: - } - } + if (fp != null) { + switch (this) { + case HEADER: + return P.p.txt.titleize(fac.getTag(fp)); + case PLAYER_NAME: + return fp.getName(); + case FACTION: + return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString(); + case LAST_SEEN: + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + case PLAYER_GROUP: + return P.p.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); + case PLAYER_BALANCE: + return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); + case PLAYER_POWER: + return String.valueOf(fp.getPowerRounded()); + case PLAYER_MAXPOWER: + return String.valueOf(fp.getPowerMaxRounded()); + case PLAYER_KILLS: + return String.valueOf(fp.getKills()); + case PLAYER_DEATHS: + return String.valueOf(fp.getDeaths()); + default: + } + } - switch (this) { - case DESCRIPTION: - return fac.getDescription(); - case FACTION: - return fac.getTag(); - case JOINING: - return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); - case PEACEFUL: - return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; - case PERMANENT: - return fac.isPermanent() ? "permanent" : "{notPermanent}"; - case CHUNKS: - return String.valueOf(fac.getLandRounded()); - case POWER: - return String.valueOf(fac.getPowerRounded()); - case MAX_POWER: - return String.valueOf(fac.getPowerMaxRounded()); - case POWER_BOOST: - double powerBoost = fac.getPowerBoost(); - return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); - case LEADER: - FPlayer fAdmin = fac.getFPlayerAdmin(); - return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); - case WARPS: - return String.valueOf(fac.getWarps().size()); - case CREATE_DATE: - return TL.sdf.format(fac.getFoundedDate()); - case RAIDABLE: - boolean raid = P.p.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded(); - return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); - case HOME_WORLD: - return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}"; - case HOME_X: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}"; - case HOME_Y: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}"; - case HOME_Z: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}"; - case LAND_VALUE: - return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value"); - case LAND_REFUND: - return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("refund"); - case BANK_BALANCE: - if (Econ.shouldBeUsed()) { - return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance"); - } - return minimal ? null : TL.ECON_OFF.format("balance"); - case ALLIES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.ALLY)); - case ENEMIES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.ENEMY)); - case TRUCES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.TRUCE)); - case ONLINE_COUNT: - if (fp != null && fp.isOnline()) { - return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); - } else { - // Only console should ever get here. - return String.valueOf(fac.getFPlayersWhereOnline(true).size()); - } - case OFFLINE_COUNT: - return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size()); - case FACTION_SIZE: - return String.valueOf(fac.getFPlayers().size()); - case FACTION_KILLS: - return String.valueOf(fac.getKills()); - case FACTION_DEATHS: - return String.valueOf(fac.getDeaths()); - case FACTION_BANCOUNT: - return String.valueOf(fac.getBannedPlayers().size()); - case FACTION_STRIKES: - return String.valueOf(fac.getStrikes()); - case FACTION_POINTS: - return String.valueOf(fac.getPoints()); + switch (this) { + case DESCRIPTION: + return fac.getDescription(); + case FACTION: + return fac.getTag(); + case JOINING: + return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); + case PEACEFUL: + return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; + case PERMANENT: + return fac.isPermanent() ? "permanent" : "{notPermanent}"; + case CHUNKS: + return String.valueOf(fac.getLandRounded()); + case POWER: + return String.valueOf(fac.getPowerRounded()); + case MAX_POWER: + return String.valueOf(fac.getPowerMaxRounded()); + case POWER_BOOST: + double powerBoost = fac.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); + case LEADER: + FPlayer fAdmin = fac.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + case WARPS: + return String.valueOf(fac.getWarps().size()); + case CREATE_DATE: + return TL.sdf.format(fac.getFoundedDate()); + case RAIDABLE: + boolean raid = P.p.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded(); + return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + case HOME_WORLD: + return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}"; + case HOME_X: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}"; + case HOME_Y: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}"; + case HOME_Z: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}"; + case LAND_VALUE: + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value"); + case LAND_REFUND: + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("refund"); + case BANK_BALANCE: + if (Econ.shouldBeUsed()) { + return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance"); + } + return minimal ? null : TL.ECON_OFF.format("balance"); + case ALLIES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.ALLY)); + case ENEMIES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.ENEMY)); + case TRUCES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.TRUCE)); + case ONLINE_COUNT: + if (fp != null && fp.isOnline()) { + return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); + } else { + // Only console should ever get here. + return String.valueOf(fac.getFPlayersWhereOnline(true).size()); + } + case OFFLINE_COUNT: + return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size()); + case FACTION_SIZE: + return String.valueOf(fac.getFPlayers().size()); + case FACTION_KILLS: + return String.valueOf(fac.getKills()); + case FACTION_DEATHS: + return String.valueOf(fac.getDeaths()); + case FACTION_BANCOUNT: + return String.valueOf(fac.getBannedPlayers().size()); + case FACTION_STRIKES: + return String.valueOf(fac.getStrikes()); + case FACTION_POINTS: + return String.valueOf(fac.getPoints()); - default: - } - return null; - } + default: + } + return null; + } - /** - * @param original raw line with variables - * @param value what to replace var in raw line with - * @return the string with the new value - */ - public String replace(String original, String value) { - return (original != null && value != null) ? original.replace(tag, value) : original; + /** + * @param original raw line with variables + * @param value what to replace var in raw line with + * @return the string with the new value + */ + public String replace(String original, String value) { + return (original != null && value != null) ? original.replace(tag, value) : original; - } + } - /** - * @param toSearch raw line with variables - * @return if the raw line contains this enums variable - */ - public boolean contains(String toSearch) { - if (tag == null) { - return false; - } - return toSearch.contains(tag); - } + /** + * @param toSearch raw line with variables + * @return if the raw line contains this enums variable + */ + public boolean contains(String toSearch) { + if (tag == null) { + return false; + } + return toSearch.contains(tag); + } - /** - * Gets the tag associated with this enum that we should replace - * - * @return the {....} variable that is located in config - */ - public String getTag() { - return this.tag; - } + /** + * Gets the tag associated with this enum that we should replace + * + * @return the {....} variable that is located in config + */ + public String getTag() { + return this.tag; + } - protected enum TagType { - FANCY(0), PLAYER(1), FACTION(2), GENERAL(3); - public int id; + protected enum TagType { + FANCY(0), PLAYER(1), FACTION(2), GENERAL(3); + public int id; - TagType(int id) { - this.id = id; - } - } + TagType(int id) { + this.id = id; + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java index b51d092a..8469a6ce 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java @@ -19,275 +19,275 @@ import static com.massivecraft.factions.zcore.util.TagReplacer.TagType; public class TagUtil { - private static final int ARBITRARY_LIMIT = 25000; + private static final int ARBITRARY_LIMIT = 25000; - /** - * Replaces all variables in a plain raw line for a faction - * - * @param faction for faction - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(Faction faction, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) { - if (tagReplacer.contains(line)) { - line = tagReplacer.replace(line, tagReplacer.getValue(faction, null)); - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a faction + * + * @param faction for faction + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(Faction faction, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) { + if (tagReplacer.contains(line)) { + line = tagReplacer.replace(line, tagReplacer.getValue(faction, null)); + } + } + return line; + } - /** - * Replaces all variables in a plain raw line for a player - * - * @param fplayer for player - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(FPlayer fplayer, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { - if (tagReplacer.contains(line)) { - String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer); - if (rep == null) { - rep = ""; // this should work, but it's not a good way to handle whatever is going wrong - } - line = tagReplacer.replace(line, rep); - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a player + * + * @param fplayer for player + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(FPlayer fplayer, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { + if (tagReplacer.contains(line)) { + String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer); + if (rep == null) { + rep = ""; // this should work, but it's not a good way to handle whatever is going wrong + } + line = tagReplacer.replace(line, rep); + } + } + return line; + } - /** - * Replaces all variables in a plain raw line for a faction, using relations from fplayer - * - * @param faction for faction - * @param fplayer from player - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(Faction faction, FPlayer fplayer, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { - if (tagReplacer.contains(line)) { - String value = tagReplacer.getValue(faction, fplayer); - if (value != null) { - line = tagReplacer.replace(line, value); - } else { - return null; // minimal show, entire line to be ignored - } - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a faction, using relations from fplayer + * + * @param faction for faction + * @param fplayer from player + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(Faction faction, FPlayer fplayer, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { + if (tagReplacer.contains(line)) { + String value = tagReplacer.getValue(faction, fplayer); + if (value != null) { + line = tagReplacer.replace(line, value); + } else { + return null; // minimal show, entire line to be ignored + } + } + } + return line; + } - /** - * Scan a line and parse the fancy variable into a fancy list - * - * @param faction for faction (viewers faction) - * @param fme for player (viewer) - * @param line fancy message prefix - * @return list of fancy msgs - */ - public static List parseFancy(Faction faction, FPlayer fme, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { - if (tagReplacer.contains(line)) { - String clean = line.replace(tagReplacer.getTag(), ""); // remove tag - return getFancy(faction, fme, tagReplacer, clean); - } - } - return null; - } + /** + * Scan a line and parse the fancy variable into a fancy list + * + * @param faction for faction (viewers faction) + * @param fme for player (viewer) + * @param line fancy message prefix + * @return list of fancy msgs + */ + public static List parseFancy(Faction faction, FPlayer fme, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { + if (tagReplacer.contains(line)) { + String clean = line.replace(tagReplacer.getTag(), ""); // remove tag + return getFancy(faction, fme, tagReplacer, clean); + } + } + return null; + } - public static String parsePlaceholders(Player player, String line) { - if (P.p.isClipPlaceholderAPIHooked() && player.isOnline()) { - line = PlaceholderAPI.setPlaceholders(player, line); - } + public static String parsePlaceholders(Player player, String line) { + if (P.p.isClipPlaceholderAPIHooked() && player.isOnline()) { + line = PlaceholderAPI.setPlaceholders(player, line); + } - if (P.p.isMVdWPlaceholderAPIHooked() && player.isOnline()) { - line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); - } + if (P.p.isMVdWPlaceholderAPIHooked() && player.isOnline()) { + line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); + } - return line; - } + return line; + } - /** - * Checks if a line has fancy variables - * - * @param line raw line from config with variables - * @return if the line has fancy variables - */ - public static boolean hasFancy(String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { - if (tagReplacer.contains(line)) { - return true; - } - } - return false; - } + /** + * Checks if a line has fancy variables + * + * @param line raw line from config with variables + * @return if the line has fancy variables + */ + public static boolean hasFancy(String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { + if (tagReplacer.contains(line)) { + return true; + } + } + return false; + } - /** - * Lets get fancy. - * - * @param target Faction to get relate from - * @param fme Player to relate to - * @param prefix First part of the fancy message - * @return list of fancy messages to send - */ - protected static List getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) { - List fancyMessages = new ArrayList<>(); - boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); + /** + * Lets get fancy. + * + * @param target Faction to get relate from + * @param fme Player to relate to + * @param prefix First part of the fancy message + * @return list of fancy messages to send + */ + protected static List getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) { + List fancyMessages = new ArrayList<>(); + boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); - switch (type) { - case ALLIES_LIST: - FancyMessage currentAllies = P.p.txt.parseFancy(prefix); - boolean firstAlly = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isAlly()) { - currentAllies.then(firstAlly ? s : ", " + s); - currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstAlly = false; - if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentAllies); - currentAllies = new FancyMessage(""); - } - } - } - fancyMessages.add(currentAllies); - return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch - case ENEMIES_LIST: - FancyMessage currentEnemies = P.p.txt.parseFancy(prefix); - boolean firstEnemy = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isEnemy()) { - currentEnemies.then(firstEnemy ? s : ", " + s); - currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstEnemy = false; - if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentEnemies); - currentEnemies = new FancyMessage(""); - } - } - } - fancyMessages.add(currentEnemies); - return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch - case TRUCES_LIST: - FancyMessage currentTruces = P.p.txt.parseFancy(prefix); - boolean firstTruce = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isTruce()) { - currentTruces.then(firstTruce ? s : ", " + s); - currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstTruce = false; - if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentTruces); - currentTruces = new FancyMessage(""); - } - } - } - fancyMessages.add(currentTruces); - return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch - case ONLINE_LIST: - FancyMessage currentOnline = P.p.txt.parseFancy(prefix); - boolean firstOnline = true; - for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { - if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { - continue; // skip - } - String name = p.getNameAndTitle(); - currentOnline.then(firstOnline ? name : ", " + name); - currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); - firstOnline = false; - if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOnline); - currentOnline = new FancyMessage(""); - } - } - fancyMessages.add(currentOnline); - return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch - case OFFLINE_LIST: - FancyMessage currentOffline = P.p.txt.parseFancy(prefix); - boolean firstOffline = true; - for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) { - String name = p.getNameAndTitle(); - // Also make sure to add players that are online BUT can't be seen. - if (!p.isOnline() || (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer()))) { - currentOffline.then(firstOffline ? name : ", " + name); - currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); - firstOffline = false; - if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOffline); - currentOffline = new FancyMessage(""); - } - } - } - fancyMessages.add(currentOffline); - return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch - case ALTS: - FancyMessage alts = P.p.txt.parseFancy(prefix); - boolean firstAlt = true; - for (FPlayer p : target.getAltPlayers()) { - String name = p.getName(); - ChatColor color; + switch (type) { + case ALLIES_LIST: + FancyMessage currentAllies = P.p.txt.parseFancy(prefix); + boolean firstAlly = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isAlly()) { + currentAllies.then(firstAlly ? s : ", " + s); + currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstAlly = false; + if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentAllies); + currentAllies = new FancyMessage(""); + } + } + } + fancyMessages.add(currentAllies); + return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch + case ENEMIES_LIST: + FancyMessage currentEnemies = P.p.txt.parseFancy(prefix); + boolean firstEnemy = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isEnemy()) { + currentEnemies.then(firstEnemy ? s : ", " + s); + currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstEnemy = false; + if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentEnemies); + currentEnemies = new FancyMessage(""); + } + } + } + fancyMessages.add(currentEnemies); + return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch + case TRUCES_LIST: + FancyMessage currentTruces = P.p.txt.parseFancy(prefix); + boolean firstTruce = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isTruce()) { + currentTruces.then(firstTruce ? s : ", " + s); + currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstTruce = false; + if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentTruces); + currentTruces = new FancyMessage(""); + } + } + } + fancyMessages.add(currentTruces); + return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch + case ONLINE_LIST: + FancyMessage currentOnline = P.p.txt.parseFancy(prefix); + boolean firstOnline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { + if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { + continue; // skip + } + String name = p.getNameAndTitle(); + currentOnline.then(firstOnline ? name : ", " + name); + currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); + firstOnline = false; + if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOnline); + currentOnline = new FancyMessage(""); + } + } + fancyMessages.add(currentOnline); + return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch + case OFFLINE_LIST: + FancyMessage currentOffline = P.p.txt.parseFancy(prefix); + boolean firstOffline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) { + String name = p.getNameAndTitle(); + // Also make sure to add players that are online BUT can't be seen. + if (!p.isOnline() || (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer()))) { + currentOffline.then(firstOffline ? name : ", " + name); + currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); + firstOffline = false; + if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOffline); + currentOffline = new FancyMessage(""); + } + } + } + fancyMessages.add(currentOffline); + return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch + case ALTS: + FancyMessage alts = P.p.txt.parseFancy(prefix); + boolean firstAlt = true; + for (FPlayer p : target.getAltPlayers()) { + String name = p.getName(); + ChatColor color; - if (p.isOnline()) { - color = ChatColor.GREEN; - } else { - color = ChatColor.RED; - } + if (p.isOnline()) { + color = ChatColor.GREEN; + } else { + color = ChatColor.RED; + } - alts.then(firstAlt ? name : ", " + name); - alts.tooltip(tipPlayer(p)).color(color); - firstAlt = false; - if (alts.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(alts); - currentOffline = new FancyMessage(""); - } + alts.then(firstAlt ? name : ", " + name); + alts.tooltip(tipPlayer(p)).color(color); + firstAlt = false; + if (alts.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(alts); + currentOffline = new FancyMessage(""); + } - } - fancyMessages.add(alts); - return firstAlt && minimal ? null : fancyMessages; - default: - break; - } - return null; - } + } + fancyMessages.add(alts); + return firstAlt && minimal ? null : fancyMessages; + default: + break; + } + return null; + } - /** - * Parses tooltip variables from config
Supports variables for factions only (type 2) - * - * @param faction faction to tooltip for - * @return list of tooltips for a fancy message - */ - private static List tipFaction(Faction faction) { - List lines = new ArrayList<>(); - for (String line : P.p.getConfig().getStringList("tooltips.list")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); - } - return lines; - } + /** + * Parses tooltip variables from config
Supports variables for factions only (type 2) + * + * @param faction faction to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipFaction(Faction faction) { + List lines = new ArrayList<>(); + for (String line : P.p.getConfig().getStringList("tooltips.list")) { + lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); + } + return lines; + } - /** - * Parses tooltip variables from config
Supports variables for players and factions (types 1 and 2) - * - * @param fplayer player to tooltip for - * @return list of tooltips for a fancy message - */ - private static List tipPlayer(FPlayer fplayer) { - List lines = new ArrayList<>(); - for (String line : P.p.getConfig().getStringList("tooltips.show")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); - } - return lines; - } + /** + * Parses tooltip variables from config
Supports variables for players and factions (types 1 and 2) + * + * @param fplayer player to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipPlayer(FPlayer fplayer) { + List lines = new ArrayList<>(); + for (String line : P.p.getConfig().getStringList("tooltips.show")) { + lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); + } + return lines; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java index c5b88478..74df651c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java @@ -10,223 +10,223 @@ import java.util.regex.Pattern; public class TextUtil { - public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); - private final static String titleizeLine = repeat("-", 52); + public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); + private final static String titleizeLine = repeat("-", 52); - // -------------------------------------------- // - // Top-level parsing functions. - // -------------------------------------------- // - private final static int titleizeBalance = -1; - public Map tags; + // -------------------------------------------- // + // Top-level parsing functions. + // -------------------------------------------- // + private final static int titleizeBalance = -1; + public Map tags; - // -------------------------------------------- // - // Tag parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Tag parsing + // -------------------------------------------- // - public TextUtil() { - this.tags = new HashMap<>(); - } + public TextUtil() { + this.tags = new HashMap<>(); + } - public static String replaceTags(String str, Map tags) { - StringBuffer ret = new StringBuffer(); - Matcher matcher = patternTag.matcher(str); - while (matcher.find()) { - String tag = matcher.group(1); - String repl = tags.get(tag); - if (repl == null) { - matcher.appendReplacement(ret, "<" + tag + ">"); - } else { - matcher.appendReplacement(ret, repl); - } - } - matcher.appendTail(ret); - return ret.toString(); - } + public static String replaceTags(String str, Map tags) { + StringBuffer ret = new StringBuffer(); + Matcher matcher = patternTag.matcher(str); + while (matcher.find()) { + String tag = matcher.group(1); + String repl = tags.get(tag); + if (repl == null) { + matcher.appendReplacement(ret, "<" + tag + ">"); + } else { + matcher.appendReplacement(ret, repl); + } + } + matcher.appendTail(ret); + return ret.toString(); + } - public static FancyMessage toFancy(String first) { - String text = ""; - FancyMessage message = new FancyMessage(text); - ChatColor color = null; - char[] chars = first.toCharArray(); + public static FancyMessage toFancy(String first) { + String text = ""; + FancyMessage message = new FancyMessage(text); + ChatColor color = null; + char[] chars = first.toCharArray(); - for (int i = 0; i < chars.length; i++) { - // changed this so javadocs wont throw an error - String compareChar = chars[i] + ""; - if (compareChar.equals("§")) { - if (color != null) { - if (color.isColor()) { - message.then(text).color(color); - } else { - message.then(text).style(color); - } - text = ""; - color = ChatColor.getByChar(chars[i + 1]); - } else { - color = ChatColor.getByChar(chars[i + 1]); - } - i++; // skip color char - } else { - text += chars[i]; - } - } - if (text.length() > 0) { - if (color != null) { - if (color.isColor()) { - message.then(text).color(color); - } else { - message.then(text).style(color); - } - } else { - message.text(text); - } - } - return message; - } + for (int i = 0; i < chars.length; i++) { + // changed this so javadocs wont throw an error + String compareChar = chars[i] + ""; + if (compareChar.equals("§")) { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + text = ""; + color = ChatColor.getByChar(chars[i + 1]); + } else { + color = ChatColor.getByChar(chars[i + 1]); + } + i++; // skip color char + } else { + text += chars[i]; + } + } + if (text.length() > 0) { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + } else { + message.text(text); + } + } + return message; + } - // -------------------------------------------- // - // Fancy parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Fancy parsing + // -------------------------------------------- // - public static String parseColor(String string) { - string = parseColorAmp(string); - string = parseColorAcc(string); - string = parseColorTags(string); - return ChatColor.translateAlternateColorCodes('&', string); - } + public static String parseColor(String string) { + string = parseColorAmp(string); + string = parseColorAcc(string); + string = parseColorTags(string); + return ChatColor.translateAlternateColorCodes('&', string); + } - public static String parseColorAmp(String string) { - string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); - string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); - string = string.replace("&&", "&"); - return string; - } + public static String parseColorAmp(String string) { + string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); + string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); + string = string.replace("&&", "&"); + return string; + } - // -------------------------------------------- // - // Color parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Color parsing + // -------------------------------------------- // - public static String parseColorAcc(String string) { - return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`plugin", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); - } + public static String parseColorAcc(String string) { + return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`plugin", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); + } - public static String parseColorTags(String string) { - return string.replace("", "").replace("", "\u00A70").replace("", "\u00A71").replace("", "\u00A72").replace("", "\u00A73").replace("", "\u00A74").replace("", "\u00A75").replace("", "\u00A76").replace("", "\u00A77").replace("", "\u00A78").replace("", "\u00A79").replace("", "\u00A7a").replace("", "\u00A7b").replace("", "\u00A7c").replace("", "\u00A7d").replace("", "\u00A7e").replace("", "\u00A7f"); - } + public static String parseColorTags(String string) { + return string.replace("", "").replace("", "\u00A70").replace("", "\u00A71").replace("", "\u00A72").replace("", "\u00A73").replace("", "\u00A74").replace("", "\u00A75").replace("", "\u00A76").replace("", "\u00A77").replace("", "\u00A78").replace("", "\u00A79").replace("", "\u00A7a").replace("", "\u00A7b").replace("", "\u00A7c").replace("", "\u00A7d").replace("", "\u00A7e").replace("", "\u00A7f"); + } - public static String upperCaseFirst(String string) { - return string.substring(0, 1).toUpperCase() + string.substring(1); - } + public static String upperCaseFirst(String string) { + return string.substring(0, 1).toUpperCase() + string.substring(1); + } - public static String implode(List list, String glue) { - StringBuilder ret = new StringBuilder(); - for (int i = 0; i < list.size(); i++) - ret.append(glue).append(list.get(i)); + public static String implode(List list, String glue) { + StringBuilder ret = new StringBuilder(); + for (int i = 0; i < list.size(); i++) + ret.append(glue).append(list.get(i)); - return ret.length() > 0 ? ret.toString().substring(glue.length()) : ""; - } + return ret.length() > 0 ? ret.toString().substring(glue.length()) : ""; + } - // -------------------------------------------- // - // Standard utils like UCFirst, implode and repeat. - // -------------------------------------------- // + // -------------------------------------------- // + // Standard utils like UCFirst, implode and repeat. + // -------------------------------------------- // - public static String repeat(String s, int times) { - return times > 0 ? s + repeat(s, times - 1) : ""; - } + public static String repeat(String s, int times) { + return times > 0 ? s + repeat(s, times - 1) : ""; + } - public static String getMaterialName(Material material) { - return material.toString().replace('_', ' ').toLowerCase(); - } + public static String getMaterialName(Material material) { + return material.toString().replace('_', ' ').toLowerCase(); + } - // -------------------------------------------- // - // Material name tools - // -------------------------------------------- // + // -------------------------------------------- // + // Material name tools + // -------------------------------------------- // - public static String getBestStartWithCI(Collection candidates, String start) { - String ret = null; - int best = 0; + public static String getBestStartWithCI(Collection candidates, String start) { + String ret = null; + int best = 0; - start = start.toLowerCase(); - int minlength = start.length(); - for (String candidate : candidates) { - if (candidate.length() < minlength) { - continue; - } - if (!candidate.toLowerCase().startsWith(start)) { - continue; - } + start = start.toLowerCase(); + int minlength = start.length(); + for (String candidate : candidates) { + if (candidate.length() < minlength) { + continue; + } + if (!candidate.toLowerCase().startsWith(start)) { + continue; + } - // The closer to zero the better - int lendiff = candidate.length() - minlength; - if (lendiff == 0) { - return candidate; - } - if (lendiff < best || best == 0) { - best = lendiff; - ret = candidate; - } - } - return ret; - } + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return candidate; + } + if (lendiff < best || best == 0) { + best = lendiff; + ret = candidate; + } + } + return ret; + } - public String parse(String str, Object... args) { - return String.format(this.parse(str), args); - } + public String parse(String str, Object... args) { + return String.format(this.parse(str), args); + } - // -------------------------------------------- // - // Paging and chrome-tools like titleize - // -------------------------------------------- // + // -------------------------------------------- // + // Paging and chrome-tools like titleize + // -------------------------------------------- // - public String parse(String str) { - return this.parseTags(parseColor(str)); - } + public String parse(String str) { + return this.parseTags(parseColor(str)); + } - public String parseTags(String str) { - return replaceTags(str, this.tags); - } + public String parseTags(String str) { + return replaceTags(str, this.tags); + } - public FancyMessage parseFancy(String prefix) { - return toFancy(parse(prefix)); - } + public FancyMessage parseFancy(String prefix) { + return toFancy(parse(prefix)); + } - public String titleize(String str) { - String center = ChatColor.DARK_GRAY + "< " + parseTags("") + str + parseTags("") + ChatColor.DARK_GRAY + " >"; - int centerlen = ChatColor.stripColor(center).length(); - int pivot = titleizeLine.length() / 2; - int eatLeft = (centerlen / 2) - titleizeBalance; - int eatRight = (centerlen - eatLeft) + titleizeBalance; + public String titleize(String str) { + String center = ChatColor.DARK_GRAY + "< " + parseTags("") + str + parseTags("") + ChatColor.DARK_GRAY + " >"; + int centerlen = ChatColor.stripColor(center).length(); + int pivot = titleizeLine.length() / 2; + int eatLeft = (centerlen / 2) - titleizeBalance; + int eatRight = (centerlen - eatLeft) + titleizeBalance; - if (eatLeft < pivot) { - return parseTags("") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight); - } else { - return parseTags("") + center; - } - } + if (eatLeft < pivot) { + return parseTags("") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight); + } else { + return parseTags("") + center; + } + } - public ArrayList getPage(List lines, int pageHumanBased, String title) { - ArrayList ret = new ArrayList<>(); - int pageZeroBased = pageHumanBased - 1; - int pageheight = 9; - int pagecount = (lines.size() / pageheight) + 1; + public ArrayList getPage(List lines, int pageHumanBased, String title) { + ArrayList ret = new ArrayList<>(); + int pageZeroBased = pageHumanBased - 1; + int pageheight = 9; + int pagecount = (lines.size() / pageheight) + 1; - ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); + ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); - if (pagecount == 0) { - ret.add(this.parseTags(TL.NOPAGES.toString())); - return ret; - } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { - ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); - return ret; - } + if (pagecount == 0) { + ret.add(this.parseTags(TL.NOPAGES.toString())); + return ret; + } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { + ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); + return ret; + } - int from = pageZeroBased * pageheight; - int to = from + pageheight; - if (to > lines.size()) { - to = lines.size(); - } + int from = pageZeroBased * pageheight; + int to = from + pageheight; + if (to > lines.size()) { + to = lines.size(); + } - ret.addAll(lines.subList(from, to)); + ret.addAll(lines.subList(from, to)); - return ret; - } + return ret; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java b/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java index 667d58b8..adf3e3a2 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java @@ -18,83 +18,83 @@ import java.util.concurrent.Callable; */ public class UUIDFetcher implements Callable> { - private static final double PROFILES_PER_REQUEST = 100; - private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; - private final JSONParser jsonParser = new JSONParser(); - private final List names; - private final boolean rateLimiting; + private static final double PROFILES_PER_REQUEST = 100; + private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; + private final JSONParser jsonParser = new JSONParser(); + private final List names; + private final boolean rateLimiting; - public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; - } + public UUIDFetcher(List names, boolean rateLimiting) { + this.names = ImmutableList.copyOf(names); + this.rateLimiting = rateLimiting; + } - public UUIDFetcher(List names) { - this(names, true); - } + public UUIDFetcher(List names) { + this(names, true); + } - private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - } + private static void writeBody(HttpURLConnection connection, String body) throws Exception { + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + } - private static HttpURLConnection createConnection() throws Exception { - URL url = new URL(PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - return connection; - } + private static HttpURLConnection createConnection() throws Exception { + URL url = new URL(PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + return connection; + } - private static UUID getUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); - } + private static UUID getUUID(String id) { + return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); + } - public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); - } + public static byte[] toBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } - public static UUID fromBytes(byte[] array) { - if (array.length != 16) { - throw new IllegalArgumentException("Illegal byte array length: " + array.length); - } - ByteBuffer byteBuffer = ByteBuffer.wrap(array); - long mostSignificant = byteBuffer.getLong(); - long leastSignificant = byteBuffer.getLong(); - return new UUID(mostSignificant, leastSignificant); - } + public static UUID fromBytes(byte[] array) { + if (array.length != 16) { + throw new IllegalArgumentException("Illegal byte array length: " + array.length); + } + ByteBuffer byteBuffer = ByteBuffer.wrap(array); + long mostSignificant = byteBuffer.getLong(); + long leastSignificant = byteBuffer.getLong(); + return new UUID(mostSignificant, leastSignificant); + } - public static UUID getUUIDOf(String name) throws Exception { - return new UUIDFetcher(Collections.singletonList(name)).call().get(name); - } + public static UUID getUUIDOf(String name) throws Exception { + return new UUIDFetcher(Collections.singletonList(name)).call().get(name); + } - public Map call() throws Exception { - Map uuidMap = new HashMap<>(); - int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); - writeBody(connection, body); - JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); - for (Object profile : array) { - JSONObject jsonProfile = (JSONObject) profile; - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (rateLimiting && i != requests - 1) { - Thread.sleep(100L); - } - } - return uuidMap; - } + public Map call() throws Exception { + Map uuidMap = new HashMap<>(); + int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + HttpURLConnection connection = createConnection(); + String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); + writeBody(connection, body); + JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); + for (Object profile : array) { + JSONObject jsonProfile = (JSONObject) profile; + String id = (String) jsonProfile.get("id"); + String name = (String) jsonProfile.get("name"); + UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (rateLimiting && i != requests - 1) { + Thread.sleep(100L); + } + } + return uuidMap; + } }