One Final Reformat

This commit is contained in:
Driftay 2019-08-24 13:21:39 -04:00
parent 72f76aeb71
commit 6a7258b692
53 changed files with 6311 additions and 6312 deletions

View File

@ -3,105 +3,105 @@ package com.massivecraft.factions.integration.dynmap;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
public class DynmapStyle { public class DynmapStyle {
// -------------------------------------------- // // -------------------------------------------- //
// FIELDS // FIELDS
// -------------------------------------------- // // -------------------------------------------- //
public String lineColor = null; public String lineColor = null;
public Double lineOpacity = null; public Double lineOpacity = null;
public Integer lineWeight = null; public Integer lineWeight = null;
public String fillColor = null; public String fillColor = null;
public Double fillOpacity = null; public Double fillOpacity = null;
// NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. // 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. // 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. // Using dynmap is optional.
public String homeMarker = null; public String homeMarker = null;
public Boolean boost = null; public Boolean boost = null;
@SafeVarargs @SafeVarargs
public static <T> T coalesce(T... items) { public static <T> T coalesce(T... items) {
for (T item : items) { for (T item : items) {
if (item != null) { if (item != null) {
return item; return item;
} }
} }
return null; return null;
} }
public static int getColor(String string) { public static int getColor(String string) {
int ret = 0x00FF00; int ret = 0x00FF00;
try { try {
ret = Integer.parseInt(string.substring(1), 16); ret = Integer.parseInt(string.substring(1), 16);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {
} }
return ret; return ret;
} }
public int getLineColor() { public int getLineColor() {
return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR)); return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR));
} }
public DynmapStyle setStrokeColor(String strokeColor) { public DynmapStyle setStrokeColor(String strokeColor) {
this.lineColor = strokeColor; this.lineColor = strokeColor;
return this; return this;
} }
public double getLineOpacity() { public double getLineOpacity() {
return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY); return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY);
} }
public DynmapStyle setLineOpacity(Double strokeOpacity) { public DynmapStyle setLineOpacity(Double strokeOpacity) {
this.lineOpacity = strokeOpacity; this.lineOpacity = strokeOpacity;
return this; return this;
} }
public int getLineWeight() { public int getLineWeight() {
return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT); return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT);
} }
public DynmapStyle setLineWeight(Integer strokeWeight) { public DynmapStyle setLineWeight(Integer strokeWeight) {
this.lineWeight = strokeWeight; this.lineWeight = strokeWeight;
return this; return this;
} }
public int getFillColor() { public int getFillColor() {
return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR)); return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR));
} }
public DynmapStyle setFillColor(String fillColor) { public DynmapStyle setFillColor(String fillColor) {
this.fillColor = fillColor; this.fillColor = fillColor;
return this; return this;
} }
public double getFillOpacity() { public double getFillOpacity() {
return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY); return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY);
} }
public DynmapStyle setFillOpacity(Double fillOpacity) { public DynmapStyle setFillOpacity(Double fillOpacity) {
this.fillOpacity = fillOpacity; this.fillOpacity = fillOpacity;
return this; return this;
} }
public String getHomeMarker() { public String getHomeMarker() {
return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER); return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER);
} }
public DynmapStyle setHomeMarker(String homeMarker) { public DynmapStyle setHomeMarker(String homeMarker) {
this.homeMarker = homeMarker; this.homeMarker = homeMarker;
return this; return this;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UTIL // UTIL
// -------------------------------------------- // // -------------------------------------------- //
public boolean getBoost() { public boolean getBoost() {
return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST); return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST);
} }
public DynmapStyle setBoost(Boolean boost) { public DynmapStyle setBoost(Boolean boost) {
this.boost = boost; this.boost = boost;
return this; return this;
} }
} }

View File

@ -4,113 +4,113 @@ import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.MarkerSet; import org.dynmap.markers.MarkerSet;
public class TempAreaMarker { public class TempAreaMarker {
// -------------------------------------------- // // -------------------------------------------- //
// FIELDS // FIELDS
// -------------------------------------------- // // -------------------------------------------- //
public String label; public String label;
public String world; public String world;
public double[] x; public double[] x;
public double[] z; public double[] z;
public String description; public String description;
public int lineColor; public int lineColor;
public double lineOpacity; public double lineOpacity;
public int lineWeight; public int lineWeight;
public int fillColor; public int fillColor;
public double fillOpacity; public double fillOpacity;
public boolean boost; public boolean boost;
// -------------------------------------------- // // -------------------------------------------- //
// CREATE // CREATE
// -------------------------------------------- // // -------------------------------------------- //
public static boolean equals(AreaMarker marker, double[] x, double[] z) { public static boolean equals(AreaMarker marker, double[] x, double[] z) {
int length = marker.getCornerCount(); int length = marker.getCornerCount();
if (x.length != length) { if (x.length != length) {
return false; return false;
} }
if (z.length != length) { if (z.length != length) {
return false; return false;
} }
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
if (marker.getCornerX(i) != x[i]) { if (marker.getCornerX(i) != x[i]) {
return false; return false;
} }
if (marker.getCornerZ(i) != z[i]) { if (marker.getCornerZ(i) != z[i]) {
return false; return false;
} }
} }
return true; return true;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE // UPDATE
// -------------------------------------------- // // -------------------------------------------- //
public AreaMarker create(MarkerSet markerset, String markerId) { public AreaMarker create(MarkerSet markerset, String markerId) {
AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent
); );
if (ret == null) { if (ret == null) {
return null; return null;
} }
// Description // Description
ret.setDescription(this.description); ret.setDescription(this.description);
// Line Style // Line Style
ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
// Fill Style // Fill Style
ret.setFillStyle(this.fillOpacity, this.fillColor); ret.setFillStyle(this.fillOpacity, this.fillColor);
// Boost Flag // Boost Flag
ret.setBoostFlag(this.boost); ret.setBoostFlag(this.boost);
return ret; return ret;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UTIL // UTIL
// -------------------------------------------- // // -------------------------------------------- //
public void update(AreaMarker marker) { public void update(AreaMarker marker) {
// Corner Locations // Corner Locations
if (!equals(marker, this.x, this.z)) { if (!equals(marker, this.x, this.z)) {
marker.setCornerLocations(this.x, this.z); marker.setCornerLocations(this.x, this.z);
} }
// Label // Label
if (!marker.getLabel().equals(this.label)) { if (!marker.getLabel().equals(this.label)) {
marker.setLabel(this.label); marker.setLabel(this.label);
} }
// Description // Description
if (!marker.getDescription().equals(this.description)) { if (!marker.getDescription().equals(this.description)) {
marker.setDescription(this.description); marker.setDescription(this.description);
} }
// Line Style // Line Style
if (marker.getLineWeight() != this.lineWeight || if (marker.getLineWeight() != this.lineWeight ||
marker.getLineOpacity() != this.lineOpacity || marker.getLineOpacity() != this.lineOpacity ||
marker.getLineColor() != this.lineColor) { marker.getLineColor() != this.lineColor) {
marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor);
} }
// Fill Style // Fill Style
if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) {
marker.setFillStyle(this.fillOpacity, this.fillColor); marker.setFillStyle(this.fillOpacity, this.fillColor);
} }
// Boost Flag // Boost Flag
if (marker.getBoostFlag() != this.boost) { if (marker.getBoostFlag() != this.boost) {
marker.setBoostFlag(this.boost); marker.setBoostFlag(this.boost);
} }
} }
} }

View File

@ -7,68 +7,68 @@ import org.dynmap.markers.MarkerIcon;
import org.dynmap.markers.MarkerSet; import org.dynmap.markers.MarkerSet;
public class TempMarker { public class TempMarker {
// -------------------------------------------- // // -------------------------------------------- //
// FIELDS // FIELDS
// -------------------------------------------- // // -------------------------------------------- //
public String label; public String label;
public String world; public String world;
public double x; public double x;
public double y; public double y;
public double z; public double z;
public String iconName; public String iconName;
public String description; public String description;
// -------------------------------------------- // // -------------------------------------------- //
// CREATE // CREATE
// -------------------------------------------- // // -------------------------------------------- //
public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) { public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) {
MarkerIcon ret = markerApi.getMarkerIcon(name); MarkerIcon ret = markerApi.getMarkerIcon(name);
if (ret == null) { if (ret == null) {
ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER); ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER);
} }
return ret; return ret;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE // UPDATE
// -------------------------------------------- // // -------------------------------------------- //
public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { 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 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) { if (ret == null) {
return null; return null;
} }
ret.setDescription(this.description); ret.setDescription(this.description);
return ret; return ret;
} }
// -------------------------------------------- // // -------------------------------------------- //
// UTIL // UTIL
// -------------------------------------------- // // -------------------------------------------- //
public void update(MarkerAPI markerApi, Marker marker) { 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()) { 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); marker.setLocation(this.world, this.x, this.y, this.z);
} }
if (!marker.getLabel().equals(this.label)) { if (!marker.getLabel().equals(this.label)) {
marker.setLabel(this.label); marker.setLabel(this.label);
} }
MarkerIcon icon = getMarkerIcon(markerApi, this.iconName); MarkerIcon icon = getMarkerIcon(markerApi, this.iconName);
if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) { if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) {
marker.setMarkerIcon(icon); marker.setMarkerIcon(icon);
} }
if (!marker.getDescription().equals(this.description)) { if (!marker.getDescription().equals(this.description)) {
marker.setDescription(this.description); marker.setDescription(this.description);
} }
} }
} }

View File

@ -5,51 +5,51 @@ import org.dynmap.markers.MarkerSet;
public class TempMarkerSet { public class TempMarkerSet {
public String label; public String label;
public int minimumZoom; public int minimumZoom;
public int priority; public int priority;
public boolean hideByDefault; public boolean hideByDefault;
public MarkerSet create(MarkerAPI markerApi, String id) { 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") MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent")
if (ret == null) { if (ret == null) {
return null; return null;
} }
// Minimum Zoom // Minimum Zoom
if (this.minimumZoom > 0) { if (this.minimumZoom > 0) {
ret.setMinZoom(this.minimumZoom); ret.setMinZoom(this.minimumZoom);
} }
// Priority // Priority
ret.setLayerPriority(this.priority); ret.setLayerPriority(this.priority);
// Hide by Default // Hide by Default
ret.setHideByDefault(this.hideByDefault); ret.setHideByDefault(this.hideByDefault);
return ret; return ret;
} }
public void update(MarkerSet markerset) { public void update(MarkerSet markerset) {
// Name // Name
if (!markerset.getMarkerSetLabel().equals(this.label)) { if (!markerset.getMarkerSetLabel().equals(this.label)) {
markerset.setMarkerSetLabel(this.label); markerset.setMarkerSetLabel(this.label);
} }
if (this.minimumZoom > 0) { if (this.minimumZoom > 0) {
if (markerset.getMinZoom() != this.minimumZoom) { if (markerset.getMinZoom() != this.minimumZoom) {
markerset.setMinZoom(this.minimumZoom); markerset.setMinZoom(this.minimumZoom);
} }
} }
if (markerset.getLayerPriority() != this.priority) { if (markerset.getLayerPriority() != this.priority) {
markerset.setLayerPriority(this.priority); markerset.setLayerPriority(this.priority);
} }
if (markerset.getHideByDefault() != this.hideByDefault) { if (markerset.getHideByDefault() != this.hideByDefault) {
markerset.setHideByDefault(this.hideByDefault); markerset.setHideByDefault(this.hideByDefault);
} }
} }
} }

View File

@ -10,32 +10,32 @@ import java.util.ListIterator;
public class FDefaultSidebar extends FSidebarProvider { public class FDefaultSidebar extends FSidebarProvider {
@Override @Override
public String getTitle(FPlayer fplayer) { public String getTitle(FPlayer fplayer) {
return replaceTags(fplayer, P.p.getConfig().getString("scoreboard.default-title", "{name}")); return replaceTags(fplayer, P.p.getConfig().getString("scoreboard.default-title", "{name}"));
} }
@Override @Override
public List<String> getLines(FPlayer fplayer) { public List<String> getLines(FPlayer fplayer) {
if (fplayer.hasFaction()) { if (fplayer.hasFaction()) {
return getOutput(fplayer, "scoreboard.default"); return getOutput(fplayer, "scoreboard.default");
} else if (P.p.getConfig().getBoolean("scoreboard.factionless-enabled", false)) { } else if (P.p.getConfig().getBoolean("scoreboard.factionless-enabled", false)) {
return getOutput(fplayer, "scoreboard.factionless"); return getOutput(fplayer, "scoreboard.factionless");
} }
return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled
} }
public List<String> getOutput(FPlayer fplayer, String list) { public List<String> getOutput(FPlayer fplayer, String list) {
List<String> lines = P.p.getConfig().getStringList(list); List<String> lines = P.p.getConfig().getStringList(list);
if (lines == null || lines.isEmpty()) { if (lines == null || lines.isEmpty()) {
return new ArrayList<>(); return new ArrayList<>();
} }
ListIterator<String> it = lines.listIterator(); ListIterator<String> it = lines.listIterator();
while (it.hasNext()) { while (it.hasNext()) {
it.set(replaceTags(fplayer, it.next())); it.set(replaceTags(fplayer, it.next()));
} }
return lines; return lines;
} }
} }

View File

@ -9,25 +9,25 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
public class FInfoSidebar extends FSidebarProvider { public class FInfoSidebar extends FSidebarProvider {
private final Faction faction; private final Faction faction;
public FInfoSidebar(Faction faction) { public FInfoSidebar(Faction faction) {
this.faction = faction; this.faction = faction;
} }
@Override @Override
public String getTitle(FPlayer fplayer) { public String getTitle(FPlayer fplayer) {
return faction.getRelationTo(fplayer).getColor() + faction.getTag(); return faction.getRelationTo(fplayer).getColor() + faction.getTag();
} }
@Override @Override
public List<String> getLines(FPlayer fplayer) { public List<String> getLines(FPlayer fplayer) {
List<String> lines = P.p.getConfig().getStringList("scoreboard.finfo"); List<String> lines = P.p.getConfig().getStringList("scoreboard.finfo");
ListIterator<String> it = lines.listIterator(); ListIterator<String> it = lines.listIterator();
while (it.hasNext()) { while (it.hasNext()) {
it.set(replaceTags(faction, fplayer, it.next())); it.set(replaceTags(faction, fplayer, it.next()));
} }
return lines; return lines;
} }
} }

View File

@ -7,14 +7,13 @@ import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean; import ch.njol.util.Kleenean;
import com.massivecraft.factions.*; import com.massivecraft.factions.*;
import org.bukkit.Chunk;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
public class PlayerChunkLocationExpression extends SimpleExpression<String> { public class PlayerChunkLocationExpression extends SimpleExpression<String> {
static{ static {
Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE,"[the] faction chunk at %player%", "[the] %player%['s] chunk"); Skript.registerExpression(PlayerChunkLocationExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction chunk at %player%", "[the] %player%['s] chunk");
} }
Expression<Player> playerExpression; Expression<Player> playerExpression;

View File

@ -18,78 +18,78 @@ import org.bukkit.event.Event;
public class PlayerFactionExpression extends SimpleExpression<String> { public class PlayerFactionExpression extends SimpleExpression<String> {
static { static {
Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction"); Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction");
} }
Expression<Player> playerExpression; Expression<Player> playerExpression;
@Override @Override
public Class<? extends String> getReturnType() { public Class<? extends String> getReturnType() {
return String.class; return String.class;
} }
@Override @Override
public boolean isSingle() { public boolean isSingle() {
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) {
playerExpression = (Expression<Player>) exprs[0]; playerExpression = (Expression<Player>) exprs[0];
return true; return true;
} }
@Override @Override
public String toString(Event event, boolean debug) { public String toString(Event event, boolean debug) {
return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug);
} }
@Override @Override
protected String[] get(Event event) { protected String[] get(Event event) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player != null) { if (player != null) {
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
return new String[]{fPlayer.getFaction().getTag()}; return new String[]{fPlayer.getFaction().getTag()};
} }
return null; return null;
} }
@Override @Override
public Class<?>[] acceptChange(final Changer.ChangeMode mode) { public Class<?>[] acceptChange(final Changer.ChangeMode mode) {
if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) {
return CollectionUtils.array(String.class); return CollectionUtils.array(String.class);
} }
return null; return null;
} }
@Override @Override
public void change(Event event, Object[] delta, Changer.ChangeMode mode) { public void change(Event event, Object[] delta, Changer.ChangeMode mode) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player == null) { if (player == null) {
return; return;
} }
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
switch (mode) { switch (mode) {
case DELETE: case DELETE:
case RESET: case RESET:
fPlayer.setFaction(Factions.getInstance().getWilderness(), false); fPlayer.setFaction(Factions.getInstance().getWilderness(), false);
break; break;
case SET: case SET:
Faction faction = Factions.getInstance().getByTag((String) delta[0]); Faction faction = Factions.getInstance().getByTag((String) delta[0]);
if (faction == null) { if (faction == null) {
faction = Factions.getInstance().getWilderness(); faction = Factions.getInstance().getWilderness();
} }
fPlayer.setFaction(faction, false); fPlayer.setFaction(faction, false);
break; break;
default: default:
} }
} }
} }

View File

@ -16,80 +16,80 @@ import org.bukkit.event.Event;
public class PlayerPowerExpression extends SimpleExpression<Number> { public class PlayerPowerExpression extends SimpleExpression<Number> {
static { static {
Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power"); Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power");
} }
Expression<Player> playerExpression; Expression<Player> playerExpression;
@Override @Override
public Class<? extends Number> getReturnType() { public Class<? extends Number> getReturnType() {
return Double.class; return Double.class;
} }
@Override @Override
public boolean isSingle() { public boolean isSingle() {
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) {
playerExpression = (Expression<Player>) exprs[0]; playerExpression = (Expression<Player>) exprs[0];
return true; return true;
} }
@Override @Override
public String toString(Event event, boolean debug) { public String toString(Event event, boolean debug) {
return "Player Power with expression player" + playerExpression.toString(event, debug); return "Player Power with expression player" + playerExpression.toString(event, debug);
} }
@Override @Override
protected Double[] get(Event event) { protected Double[] get(Event event) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player != null) { if (player != null) {
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
return new Double[]{fPlayer.getFaction().getPower()}; return new Double[]{fPlayer.getFaction().getPower()};
} }
return null; return null;
} }
@Override @Override
public Class<?>[] acceptChange(final Changer.ChangeMode mode) { public Class<?>[] acceptChange(final Changer.ChangeMode mode) {
if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) { if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) {
return CollectionUtils.array(Number.class); return CollectionUtils.array(Number.class);
} }
return null; return null;
} }
@Override @Override
public void change(Event event, Object[] delta, Changer.ChangeMode mode) { public void change(Event event, Object[] delta, Changer.ChangeMode mode) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player == null) { if (player == null) {
return; return;
} }
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
switch (mode) { switch (mode) {
case ADD: case ADD:
fPlayer.alterPower(Double.valueOf((Long) delta[0])); fPlayer.alterPower(Double.valueOf((Long) delta[0]));
break; break;
case REMOVE: case REMOVE:
fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1); fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1);
break; break;
case RESET: case RESET:
fPlayer.alterPower(fPlayer.getPowerMax() * -1); fPlayer.alterPower(fPlayer.getPowerMax() * -1);
break; break;
default: default:
} }
} }
} }

View File

@ -16,77 +16,77 @@ import org.bukkit.event.Event;
public class PlayerRoleExpression extends SimpleExpression<String> { public class PlayerRoleExpression extends SimpleExpression<String> {
static { static {
Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role"); Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role");
} }
Expression<Player> playerExpression; Expression<Player> playerExpression;
@Override @Override
public Class<? extends String> getReturnType() { public Class<? extends String> getReturnType() {
return String.class; return String.class;
} }
@Override @Override
public boolean isSingle() { public boolean isSingle() {
return true; return true;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) {
playerExpression = (Expression<Player>) exprs[0]; playerExpression = (Expression<Player>) exprs[0];
return true; return true;
} }
@Override @Override
public String toString(Event event, boolean debug) { public String toString(Event event, boolean debug) {
return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug);
} }
@Override @Override
protected String[] get(Event event) { protected String[] get(Event event) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player != null) { if (player != null) {
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
return new String[]{fPlayer.getRole().toString()}; return new String[]{fPlayer.getRole().toString()};
} }
return null; return null;
} }
@Override @Override
public Class<?>[] acceptChange(final Changer.ChangeMode mode) { public Class<?>[] acceptChange(final Changer.ChangeMode mode) {
if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) {
return CollectionUtils.array(String.class); return CollectionUtils.array(String.class);
} }
return null; return null;
} }
@Override @Override
public void change(Event event, Object[] delta, Changer.ChangeMode mode) { public void change(Event event, Object[] delta, Changer.ChangeMode mode) {
Player player = playerExpression.getSingle(event); Player player = playerExpression.getSingle(event);
if (player == null) { if (player == null) {
return; return;
} }
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
switch (mode) { switch (mode) {
case DELETE: case DELETE:
case RESET: case RESET:
fPlayer.setRole(Role.RECRUIT); fPlayer.setRole(Role.RECRUIT);
break; break;
case SET: case SET:
fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase())); fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase()));
break; break;
default: default:
} }
} }
} }

View File

@ -3,42 +3,44 @@ package com.massivecraft.factions.zcore.fperms;
import com.massivecraft.factions.P; import com.massivecraft.factions.P;
public enum Access { public enum Access {
ALLOW("Allow"), ALLOW("Allow"),
DENY("Deny"), DENY("Deny"),
UNDEFINED("Undefined"); UNDEFINED("Undefined");
private final String name; private final String name;
Access(String name) { Access(String name) {
this.name = name; this.name = name;
} }
/** /**
* Case insensitive check for access. * Case insensitive check for access.
* *
* @param check * @param check
* @return * @return
*/ */
public static Access fromString(String check) { public static Access fromString(String check) {
for (Access access : values()) for (Access access : values())
if (access.name().equalsIgnoreCase(check)) if (access.name().equalsIgnoreCase(check))
return access; return access;
return null; return null;
} }
public String getName() { public static Access booleanToAccess(boolean access) {
return this.name.toLowerCase(); if (access) return Access.ALLOW;
} else return Access.DENY;
}
@Override public String getName() {
public String toString() { return this.name.toLowerCase();
return name(); }
}
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) { public String getColor() {
if (access) return Access.ALLOW; return P.p.getConfig().getString("fperm-gui.action.Access-Colors." + this.name);
else return Access.DENY; }
}
} }

View File

@ -1,160 +1,157 @@
package com.massivecraft.factions.zcore.fperms; package com.massivecraft.factions.zcore.fperms;
import com.massivecraft.factions.util.XMaterial;
import javafx.scene.paint.Material;
public class DefaultPermissions { public class DefaultPermissions {
public boolean ban; public boolean ban;
public boolean build; public boolean build;
public boolean destroy; public boolean destroy;
public boolean frostwalk; public boolean frostwalk;
public boolean painbuild; public boolean painbuild;
public boolean door; public boolean door;
public boolean button; public boolean button;
public boolean lever; public boolean lever;
public boolean container; public boolean container;
public boolean invite; public boolean invite;
public boolean kick; public boolean kick;
public boolean items; public boolean items;
public boolean sethome; public boolean sethome;
public boolean territory; public boolean territory;
public boolean access; public boolean access;
public boolean home; public boolean home;
public boolean disband; public boolean disband;
public boolean promote; public boolean promote;
public boolean setwarp; public boolean setwarp;
public boolean warp; public boolean warp;
public boolean fly; public boolean fly;
public boolean vault; public boolean vault;
public boolean tntbank; public boolean tntbank;
public boolean tntfill; public boolean tntfill;
public boolean withdraw; public boolean withdraw;
public boolean chest; public boolean chest;
public boolean check; public boolean check;
public boolean spawner; public boolean spawner;
public DefaultPermissions() { public DefaultPermissions() {
} }
public DefaultPermissions(boolean def) { public DefaultPermissions(boolean def) {
this.ban = def; this.ban = def;
this.build = def; this.build = def;
this.destroy = def; this.destroy = def;
this.frostwalk = def; this.frostwalk = def;
this.painbuild = def; this.painbuild = def;
this.door = def; this.door = def;
this.button = def; this.button = def;
this.lever = def; this.lever = def;
this.container = def; this.container = def;
this.invite = def; this.invite = def;
this.kick = def; this.kick = def;
this.items = def; this.items = def;
this.sethome = def; this.sethome = def;
this.territory = def; this.territory = def;
this.access = def; this.access = def;
this.home = def; this.home = def;
this.disband = def; this.disband = def;
this.promote = def; this.promote = def;
this.setwarp = def; this.setwarp = def;
this.warp = def; this.warp = def;
this.fly = def; this.fly = def;
this.vault = def; this.vault = def;
this.tntbank = def; this.tntbank = def;
this.tntfill = def; this.tntfill = def;
this.withdraw = def; this.withdraw = def;
this.chest = def; this.chest = def;
this.check = def; this.check = def;
this.spawner = def; this.spawner = def;
} }
public DefaultPermissions(boolean canBan, public DefaultPermissions(boolean canBan,
boolean canBuild, boolean canBuild,
boolean canDestory, boolean canDestory,
boolean canFrostwalk, boolean canFrostwalk,
boolean canPainbuild, boolean canPainbuild,
boolean canDoor, boolean canDoor,
boolean canButton, boolean canButton,
boolean canLever, boolean canLever,
boolean canContainer, boolean canContainer,
boolean canInvite, boolean canInvite,
boolean canKick, boolean canKick,
boolean canItems, boolean canItems,
boolean canSethome, boolean canSethome,
boolean canTerritory, boolean canTerritory,
boolean canAccess, boolean canAccess,
boolean canHome, boolean canHome,
boolean canDisband, boolean canDisband,
boolean canPromote, boolean canPromote,
boolean canSetwarp, boolean canSetwarp,
boolean canWarp, boolean canWarp,
boolean canFly, boolean canFly,
boolean canVault, boolean canVault,
boolean canTntbank, boolean canTntbank,
boolean canTntfill, boolean canTntfill,
boolean canWithdraw, boolean canWithdraw,
boolean canChest, boolean canChest,
boolean canCheck, boolean canCheck,
boolean canSpawners) { boolean canSpawners) {
this.ban = canBan; this.ban = canBan;
this.build = canBuild; this.build = canBuild;
this.destroy = canDestory; this.destroy = canDestory;
this.frostwalk = canFrostwalk; this.frostwalk = canFrostwalk;
this.painbuild = canPainbuild; this.painbuild = canPainbuild;
this.door = canDoor; this.door = canDoor;
this.button = canButton; this.button = canButton;
this.lever = canLever; this.lever = canLever;
this.container = canContainer; this.container = canContainer;
this.invite = canInvite; this.invite = canInvite;
this.kick = canKick; this.kick = canKick;
this.items = canItems; this.items = canItems;
this.sethome = canSethome; this.sethome = canSethome;
this.territory = canTerritory; this.territory = canTerritory;
this.access = canAccess; this.access = canAccess;
this.home = canHome; this.home = canHome;
this.disband = canDisband; this.disband = canDisband;
this.promote = canPromote; this.promote = canPromote;
this.setwarp = canSetwarp; this.setwarp = canSetwarp;
this.warp = canWarp; this.warp = canWarp;
this.fly = canFly; this.fly = canFly;
this.vault = canVault; this.vault = canVault;
this.tntbank = canTntbank; this.tntbank = canTntbank;
this.tntfill = canTntfill; this.tntfill = canTntfill;
this.withdraw = canWithdraw; this.withdraw = canWithdraw;
this.chest = canChest; this.chest = canChest;
this.check = canCheck; this.check = canCheck;
this.spawner = canSpawners; this.spawner = canSpawners;
} }
@Deprecated @Deprecated
public boolean getbyName(String name) { public boolean getbyName(String name) {
if (name == "ban") return this.ban; if (name == "ban") return this.ban;
else if (name == "build") return this.build; else if (name == "build") return this.build;
else if (name == "destroy") return this.destroy; else if (name == "destroy") return this.destroy;
else if (name == "frostwalk") return this.frostwalk; else if (name == "frostwalk") return this.frostwalk;
else if (name == "painbuild") return this.painbuild; else if (name == "painbuild") return this.painbuild;
else if (name == "door") return this.door; else if (name == "door") return this.door;
else if (name == "button") return this.button; else if (name == "button") return this.button;
else if (name == "lever") return this.lever; else if (name == "lever") return this.lever;
else if (name == "home") return this.home; else if (name == "home") return this.home;
else if (name == "container") return this.container; else if (name == "container") return this.container;
else if (name == "invite") return this.invite; else if (name == "invite") return this.invite;
else if (name == "kick") return this.kick; else if (name == "kick") return this.kick;
else if (name == "items") return this.items; else if (name == "items") return this.items;
else if (name == "sethome") return this.sethome; else if (name == "sethome") return this.sethome;
else if (name == "territory") return this.territory; else if (name == "territory") return this.territory;
else if (name == "access") return this.access; else if (name == "access") return this.access;
else if (name == "disband") return this.disband; else if (name == "disband") return this.disband;
else if (name == "promote") return this.promote; else if (name == "promote") return this.promote;
else if (name == "setwarp") return this.setwarp; else if (name == "setwarp") return this.setwarp;
else if (name == "warp") return this.warp; else if (name == "warp") return this.warp;
else if (name == "fly") return this.fly; else if (name == "fly") return this.fly;
else if (name == "vault") return this.vault; else if (name == "vault") return this.vault;
else if (name == "tntbank") return this.tntbank; else if (name == "tntbank") return this.tntbank;
else if (name == "tntfill") return this.tntfill; else if (name == "tntfill") return this.tntfill;
else if (name == "withdraw") return this.withdraw; else if (name == "withdraw") return this.withdraw;
else if (name == "chest") return this.chest; else if (name == "chest") return this.chest;
else if(name == "check") return this.check; else if (name == "check") return this.check;
else if (name == "spawner") return this.spawner; else if (name == "spawner") return this.spawner;
else return false; else return false;
} }
} }

View File

@ -4,10 +4,10 @@ import org.bukkit.inventory.ItemStack;
public interface Permissable { public interface Permissable {
ItemStack buildItem(); ItemStack buildItem();
String replacePlaceholders(String string); String replacePlaceholders(String string);
String name(); String name();
} }

View File

@ -13,103 +13,105 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public enum PermissableAction { public enum PermissableAction {
BAN("ban"), BAN("ban"),
BUILD("build"), BUILD("build"),
DESTROY("destroy"), DESTROY("destroy"),
FROST_WALK("frostwalk"), FROST_WALK("frostwalk"),
PAIN_BUILD("painbuild"), PAIN_BUILD("painbuild"),
DOOR("door"), DOOR("door"),
BUTTON("button"), BUTTON("button"),
LEVER("lever"), LEVER("lever"),
CONTAINER("container"), CONTAINER("container"),
INVITE("invite"), INVITE("invite"),
KICK("kick"), KICK("kick"),
ITEM("items"), // generic for most items ITEM("items"), // generic for most items
SETHOME("sethome"), SETHOME("sethome"),
TERRITORY("territory"), TERRITORY("territory"),
ACCESS("access"), ACCESS("access"),
HOME("home"), HOME("home"),
DISBAND("disband"), DISBAND("disband"),
PROMOTE("promote"), PROMOTE("promote"),
SETWARP("setwarp"), SETWARP("setwarp"),
WARP("warp"), WARP("warp"),
FLY("fly"), FLY("fly"),
VAULT("vault"), VAULT("vault"),
TNTBANK("tntbank"), TNTBANK("tntbank"),
TNTFILL("tntfill"), TNTFILL("tntfill"),
WITHDRAW("withdraw"), WITHDRAW("withdraw"),
CHEST("chest"), CHEST("chest"),
CHECK("check"), CHECK("check"),
SPAWNER("spawner"); SPAWNER("spawner");
private String name; private String name;
PermissableAction(String name) { PermissableAction(String name) {
this.name = name; this.name = name;
} }
/** /**
* Case insensitive check for action. * Case insensitive check for action.
* *
* @param check * @param check
* @return - action * @return - action
*/ */
public static PermissableAction fromString(String check) { public static PermissableAction fromString(String check) {
for (PermissableAction permissableAction : values()) { for (PermissableAction permissableAction : values()) {
if (permissableAction.name().equalsIgnoreCase(check)) { if (permissableAction.name().equalsIgnoreCase(check)) {
return permissableAction; return permissableAction;
} }
} }
return null; return null;
} }
public int getSlot() { return P.p.getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase()); } public static Map<PermissableAction, Access> fromDefaults(DefaultPermissions defaultPermissions) {
Map<PermissableAction, Access> defaultMap = new HashMap<>();
for (PermissableAction permissableAction : PermissableAction.values()) {
defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY);
}
return defaultMap;
}
public static Map<PermissableAction, Access> fromDefaults(DefaultPermissions defaultPermissions) { public static PermissableAction fromSlot(int slot) {
Map<PermissableAction, Access> defaultMap = new HashMap<>(); for (PermissableAction action : PermissableAction.values()) {
for (PermissableAction permissableAction : PermissableAction.values()) { if (action.getSlot() == slot) return action;
defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY); }
} return null;
return defaultMap; }
}
/** public int getSlot() {
* Get the friendly name of this action. Used for editing in commands. return P.p.getConfig().getInt("fperm-gui.action.slots." + this.name.toLowerCase());
* }
* @return friendly name of the action as a String.
*/
public String getName() {
return this.name;
}
@Override /**
public String toString() { * Get the friendly name of this action. Used for editing in commands.
return name; *
} * @return friendly name of the action as a String.
*/
public String getName() {
return this.name;
}
public ItemStack buildAsset(FPlayer fme, Permissable perm) { @Override
ConfigurationSection section = P.p.getConfig().getConfigurationSection("fperm-gui.action"); public String toString() {
ItemStack item = XMaterial.matchXMaterial(section.getString("Materials." + this.name)).parseItem(); return name;
ItemMeta meta = item.getItemMeta(); }
meta.setDisplayName(P.p.color(section.getString("placeholder-item.name").replace("{action}", this.name))); public ItemStack buildAsset(FPlayer fme, Permissable perm) {
List<String> lore = section.getStringList("placeholder-item.lore"); 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, meta.setDisplayName(P.p.color(section.getString("placeholder-item.name").replace("{action}", this.name)));
new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()), List<String> lore = section.getStringList("placeholder-item.lore");
new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName()));
meta.setLore(P.p.colorList(lore)); lore = P.p.replacePlaceholders(lore,
item.setItemMeta(meta); new Placeholder("{action-access-color}", fme.getFaction().getPermissions().get(perm).get(this).getColor()),
return item; new Placeholder("{action-access}", fme.getFaction().getPermissions().get(perm).get(this).getName()));
}
public static PermissableAction fromSlot(int slot) { meta.setLore(P.p.colorList(lore));
for (PermissableAction action : PermissableAction.values()) { item.setItemMeta(meta);
if (action.getSlot() == slot) return action; return item;
} }
return null;
}
} }

View File

@ -18,62 +18,62 @@ import java.util.concurrent.ThreadLocalRandom;
public class CropUpgrades implements Listener { public class CropUpgrades implements Listener {
@EventHandler @EventHandler
public void onCropGrow(BlockGrowEvent e) { public void onCropGrow(BlockGrowEvent e) {
FLocation floc = new FLocation(e.getBlock().getLocation()); FLocation floc = new FLocation(e.getBlock().getLocation());
Faction factionAtLoc = Board.getInstance().getFactionAt(floc); Faction factionAtLoc = Board.getInstance().getFactionAt(floc);
if (!factionAtLoc.isWilderness()) { if (!factionAtLoc.isWilderness()) {
int level = factionAtLoc.getUpgrade(UpgradeType.CROP); int level = factionAtLoc.getUpgrade(UpgradeType.CROP);
if (level != 0) { if (level != 0) {
int chance = -1; int chance = -1;
switch (level) { switch (level) {
case 1: case 1:
chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1");
break; break;
case 2: case 2:
chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2");
break; break;
case 3: case 3:
chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); chance = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3");
break; break;
} }
if (chance >= 0) { if (chance >= 0) {
int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1); int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1);
if (randomNum <= chance) if (randomNum <= chance)
growCrop(e); growCrop(e);
} }
} }
} }
} }
private void growCrop(BlockGrowEvent e) { private void growCrop(BlockGrowEvent e) {
if (e.getBlock().getType().equals(XMaterial.WHEAT.parseMaterial())) { if (e.getBlock().getType().equals(XMaterial.WHEAT.parseMaterial())) {
e.setCancelled(true); e.setCancelled(true);
Crops c = new Crops(CropState.RIPE); Crops c = new Crops(CropState.RIPE);
BlockState bs = e.getBlock().getState(); BlockState bs = e.getBlock().getState();
bs.setData(c); bs.setData(c);
bs.update(); 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()) { if (below.getType() == XMaterial.SUGAR_CANE.parseMaterial()) {
Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); 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) { if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) {
above.setType(XMaterial.SUGAR_CANE.parseMaterial()); above.setType(XMaterial.SUGAR_CANE.parseMaterial());
} }
} else if (below.getType() == Material.CACTUS) { } else if (below.getType() == Material.CACTUS) {
Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); 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) { if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) {
above.setType(Material.CACTUS); above.setType(Material.CACTUS);
} }
} }
} }
} }

View File

@ -11,42 +11,42 @@ import org.bukkit.event.entity.EntityDeathEvent;
public class EXPUpgrade implements Listener { public class EXPUpgrade implements Listener {
@EventHandler @EventHandler
public void onDeath(EntityDeathEvent e) { public void onDeath(EntityDeathEvent e) {
Entity killer = e.getEntity().getKiller(); Entity killer = e.getEntity().getKiller();
if (killer == null) if (killer == null)
return; return;
FLocation floc = new FLocation(e.getEntity().getLocation()); FLocation floc = new FLocation(e.getEntity().getLocation());
Faction faction = Board.getInstance().getFactionAt(floc); Faction faction = Board.getInstance().getFactionAt(floc);
if (!faction.isWilderness()) { if (!faction.isWilderness()) {
int level = faction.getUpgrade(UpgradeType.EXP); int level = faction.getUpgrade(UpgradeType.EXP);
if (level != 0) { if (level != 0) {
double multiplier = -1; double multiplier = -1;
switch (level) { switch (level) {
case 1: case 1:
multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1");
break; break;
case 2: case 2:
multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2");
break; break;
case 3: case 3:
multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); multiplier = P.p.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3");
break; break;
} }
if (multiplier >= 0) if (multiplier >= 0)
spawnMoreExp(e, multiplier); spawnMoreExp(e, multiplier);
} }
} }
} }
private void spawnMoreExp(EntityDeathEvent e, double multiplier) { private void spawnMoreExp(EntityDeathEvent e, double multiplier) {
double newExp = e.getDroppedExp() * multiplier; double newExp = e.getDroppedExp() * multiplier;
e.setDroppedExp((int) newExp); e.setDroppedExp((int) newExp);
} }
} }

View File

@ -173,13 +173,13 @@ public class FUpgradesGUI implements Listener {
break; break;
} }
} }
} else if(e.getCurrentItem().equals(memberItem)){ } else if (e.getCurrentItem().equals(memberItem)) {
int memberLevel = fme.getFaction().getUpgrade(UpgradeType.MEMBERS) + 1; 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; return;
} }
int cost = P.p.getConfig().getInt("fupgrades.MainMenu.Members.Cost.level-" + memberLevel); 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.getFaction().setUpgrade(UpgradeType.MEMBERS, memberLevel);
fme.getPlayer().closeInventory(); fme.getPlayer().closeInventory();
takeMoney(fme, cost); 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")); Material cropMaterial = Material.getMaterial(P.p.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type"));
int cropAmt = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); int cropAmt = P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount");
short cropData = Short.parseShort(P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); short cropData = Short.parseShort(P.p.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + "");

View File

@ -10,32 +10,32 @@ import org.bukkit.event.entity.SpawnerSpawnEvent;
public class SpawnerUpgrades implements Listener { public class SpawnerUpgrades implements Listener {
@EventHandler @EventHandler
public void onSpawn(SpawnerSpawnEvent e) { public void onSpawn(SpawnerSpawnEvent e) {
FLocation floc = new FLocation(e.getLocation()); FLocation floc = new FLocation(e.getLocation());
Faction factionAtLoc = Board.getInstance().getFactionAt(floc); Faction factionAtLoc = Board.getInstance().getFactionAt(floc);
if (!factionAtLoc.isWilderness()) { if (!factionAtLoc.isWilderness()) {
int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER); int level = factionAtLoc.getUpgrade(UpgradeType.SPAWNER);
if (level != 0) { if (level != 0) {
switch (level) { switch (level) {
case 1: case 1:
lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1"));
break; break;
case 2: case 2:
lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2"));
break; break;
case 3: case 3:
lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); lowerSpawnerDelay(e, P.p.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3"));
break; break;
} }
} }
} }
} }
private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) { private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) {
int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier); int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier);
e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby); e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby);
} }
} }

View File

@ -2,16 +2,16 @@ package com.massivecraft.factions.zcore.fupgrades;
public enum UpgradeType { 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) { UpgradeType(String id) {
this.id = id; this.id = id;
} }
@Override @Override
public String toString() { public String toString() {
return this.id; return this.id;
} }
} }

View File

@ -7,191 +7,191 @@ import java.util.Set;
public class NBTCompound { public class NBTCompound {
private String compundName; private String compundName;
private NBTCompound parent; private NBTCompound parent;
protected NBTCompound() { protected NBTCompound() {
} }
protected NBTCompound(NBTCompound owner, String name) { protected NBTCompound(NBTCompound owner, String name) {
this.compundName = name; this.compundName = name;
this.parent = owner; this.parent = owner;
} }
public String getName() { public String getName() {
return compundName; return compundName;
} }
protected Object getCompound() { protected Object getCompound() {
return parent.getCompound(); return parent.getCompound();
} }
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
parent.setCompound(compound); parent.setCompound(compound);
} }
public NBTCompound getParent() { public NBTCompound getParent() {
return parent; return parent;
} }
public void mergeCompound(NBTCompound comp) { public void mergeCompound(NBTCompound comp) {
NBTReflectionUtil.addOtherNBTCompound(this, comp); NBTReflectionUtil.addOtherNBTCompound(this, comp);
} }
public void setString(String key, String value) { public void setString(String key, String value) {
NBTReflectionUtil.setString(this, key, value); NBTReflectionUtil.setString(this, key, value);
} }
public String getString(String key) { public String getString(String key) {
return NBTReflectionUtil.getString(this, key); return NBTReflectionUtil.getString(this, key);
} }
protected String getContent(String key) { protected String getContent(String key) {
return NBTReflectionUtil.getContent(this, key); return NBTReflectionUtil.getContent(this, key);
} }
public void setInteger(String key, Integer value) { public void setInteger(String key, Integer value) {
NBTReflectionUtil.setInt(this, key, value); NBTReflectionUtil.setInt(this, key, value);
} }
public Integer getInteger(String key) { public Integer getInteger(String key) {
return NBTReflectionUtil.getInt(this, key); return NBTReflectionUtil.getInt(this, key);
} }
public void setDouble(String key, Double value) { public void setDouble(String key, Double value) {
NBTReflectionUtil.setDouble(this, key, value); NBTReflectionUtil.setDouble(this, key, value);
} }
public Double getDouble(String key) { public Double getDouble(String key) {
return NBTReflectionUtil.getDouble(this, key); return NBTReflectionUtil.getDouble(this, key);
} }
public void setByte(String key, Byte value) { public void setByte(String key, Byte value) {
NBTReflectionUtil.setByte(this, key, value); NBTReflectionUtil.setByte(this, key, value);
} }
public Byte getByte(String key) { public Byte getByte(String key) {
return NBTReflectionUtil.getByte(this, key); return NBTReflectionUtil.getByte(this, key);
} }
public void setShort(String key, Short value) { public void setShort(String key, Short value) {
NBTReflectionUtil.setShort(this, key, value); NBTReflectionUtil.setShort(this, key, value);
} }
public Short getShort(String key) { public Short getShort(String key) {
return NBTReflectionUtil.getShort(this, key); return NBTReflectionUtil.getShort(this, key);
} }
public void setLong(String key, Long value) { public void setLong(String key, Long value) {
NBTReflectionUtil.setLong(this, key, value); NBTReflectionUtil.setLong(this, key, value);
} }
public Long getLong(String key) { public Long getLong(String key) {
return NBTReflectionUtil.getLong(this, key); return NBTReflectionUtil.getLong(this, key);
} }
public void setFloat(String key, Float value) { public void setFloat(String key, Float value) {
NBTReflectionUtil.setFloat(this, key, value); NBTReflectionUtil.setFloat(this, key, value);
} }
public Float getFloat(String key) { public Float getFloat(String key) {
return NBTReflectionUtil.getFloat(this, key); return NBTReflectionUtil.getFloat(this, key);
} }
public void setByteArray(String key, byte[] value) { public void setByteArray(String key, byte[] value) {
NBTReflectionUtil.setByteArray(this, key, value); NBTReflectionUtil.setByteArray(this, key, value);
} }
public byte[] getByteArray(String key) { public byte[] getByteArray(String key) {
return NBTReflectionUtil.getByteArray(this, key); return NBTReflectionUtil.getByteArray(this, key);
} }
public void setIntArray(String key, int[] value) { public void setIntArray(String key, int[] value) {
NBTReflectionUtil.setIntArray(this, key, value); NBTReflectionUtil.setIntArray(this, key, value);
} }
public int[] getIntArray(String key) { public int[] getIntArray(String key) {
return NBTReflectionUtil.getIntArray(this, key); return NBTReflectionUtil.getIntArray(this, key);
} }
public void setBoolean(String key, Boolean value) { public void setBoolean(String key, Boolean value) {
NBTReflectionUtil.setBoolean(this, key, value); NBTReflectionUtil.setBoolean(this, key, value);
} }
protected void set(String key, Object val) { protected void set(String key, Object val) {
NBTReflectionUtil.set(this, key, val); NBTReflectionUtil.set(this, key, val);
} }
public Boolean getBoolean(String key) { public Boolean getBoolean(String key) {
return NBTReflectionUtil.getBoolean(this, key); return NBTReflectionUtil.getBoolean(this, key);
} }
public void setObject(String key, Object value) { public void setObject(String key, Object value) {
NBTReflectionUtil.setObject(this, key, value); NBTReflectionUtil.setObject(this, key, value);
} }
public <T> T getObject(String key, Class<T> type) { public <T> T getObject(String key, Class<T> type) {
return NBTReflectionUtil.getObject(this, key, type); return NBTReflectionUtil.getObject(this, key, type);
} }
public Boolean hasKey(String key) { public Boolean hasKey(String key) {
return NBTReflectionUtil.hasKey(this, key); return NBTReflectionUtil.hasKey(this, key);
} }
public void removeKey(String key) { public void removeKey(String key) {
NBTReflectionUtil.remove(this, key); NBTReflectionUtil.remove(this, key);
} }
public Set<String> getKeys() { public Set<String> getKeys() {
return NBTReflectionUtil.getKeys(this); return NBTReflectionUtil.getKeys(this);
} }
public NBTCompound addCompound(String name) { public NBTCompound addCompound(String name) {
NBTReflectionUtil.addNBTTagCompound(this, name); NBTReflectionUtil.addNBTTagCompound(this, name);
return getCompound(name); return getCompound(name);
} }
public NBTCompound getCompound(String name) { public NBTCompound getCompound(String name) {
NBTCompound next = new NBTCompound(this, name); NBTCompound next = new NBTCompound(this, name);
if (NBTReflectionUtil.valideCompound(next)) return next; if (NBTReflectionUtil.valideCompound(next)) return next;
return null; return null;
} }
public NBTList getList(String name, NBTType type) { public NBTList getList(String name, NBTType type) {
return NBTReflectionUtil.getList(this, name, type); return NBTReflectionUtil.getList(this, name, type);
} }
public NBTType getType(String name) { public NBTType getType(String name) {
if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4)
return NBTType.NBTTagEnd; return NBTType.NBTTagEnd;
return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); return NBTType.valueOf(NBTReflectionUtil.getType(this, name));
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (String key : getKeys()) { for (String key : getKeys()) {
result.append(toString(key)); result.append(toString(key));
} }
return result.toString(); return result.toString();
} }
public String toString(String key) { public String toString(String key) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
NBTCompound compound = this; NBTCompound compound = this;
while (compound.getParent() != null) { while (compound.getParent() != null) {
result.append(" "); result.append(" ");
compound = compound.getParent(); compound = compound.getParent();
} }
if (this.getType(key) == NBTType.NBTTagCompound) { if (this.getType(key) == NBTType.NBTTagCompound) {
return this.getCompound(key).toString(); return this.getCompound(key).toString();
} else { } else {
return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); return result + "-" + key + ": " + getContent(key) + System.lineSeparator();
} }
} }
public String asNBTString() { public String asNBTString() {
return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); return NBTReflectionUtil.gettoCompount(getCompound(), this).toString();
} }
} }

View File

@ -2,31 +2,31 @@ package com.massivecraft.factions.zcore.nbtapi;
public class NBTContainer extends NBTCompound { public class NBTContainer extends NBTCompound {
private Object nbt; private Object nbt;
public NBTContainer() { public NBTContainer() {
this(NBTReflectionUtil.getNewNBTTag()); this(NBTReflectionUtil.getNewNBTTag());
} }
protected NBTContainer(Object nbt) { protected NBTContainer(Object nbt) {
this.nbt = nbt; this.nbt = nbt;
} }
public NBTContainer(String nbtString) throws IllegalArgumentException { public NBTContainer(String nbtString) throws IllegalArgumentException {
try { try {
nbt = NBTReflectionUtil.parseNBT(nbtString); nbt = NBTReflectionUtil.parseNBT(nbtString);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); throw new IllegalArgumentException("Malformed Json: " + ex.getMessage());
} }
} }
protected Object getCompound() { protected Object getCompound() {
return nbt; return nbt;
} }
protected void setCompound(Object tag) { protected void setCompound(Object tag) {
nbt = tag; nbt = tag;
} }
} }

View File

@ -4,18 +4,18 @@ import org.bukkit.entity.Entity;
public class NBTEntity extends NBTCompound { public class NBTEntity extends NBTCompound {
private final Entity ent; private final Entity ent;
public NBTEntity(Entity entity) { public NBTEntity(Entity entity) {
ent = entity; ent = entity;
} }
protected Object getCompound() { protected Object getCompound() {
return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent));
} }
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent));
} }
} }

View File

@ -7,39 +7,39 @@ import java.io.IOException;
public class NBTFile extends NBTCompound { public class NBTFile extends NBTCompound {
private final File file; private final File file;
private Object nbt; private Object nbt;
public NBTFile(File file) throws IOException { public NBTFile(File file) throws IOException {
this.file = file; this.file = file;
if (file.exists()) { if (file.exists()) {
FileInputStream inputsteam = new FileInputStream(file); FileInputStream inputsteam = new FileInputStream(file);
nbt = NBTReflectionUtil.readNBTFile(inputsteam); nbt = NBTReflectionUtil.readNBTFile(inputsteam);
} else { } else {
nbt = NBTReflectionUtil.getNewNBTTag(); nbt = NBTReflectionUtil.getNewNBTTag();
save(); save();
} }
} }
public void save() throws IOException { public void save() throws IOException {
if (!file.exists()) { if (!file.exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
file.createNewFile(); file.createNewFile();
} }
FileOutputStream outStream = new FileOutputStream(file); FileOutputStream outStream = new FileOutputStream(file);
NBTReflectionUtil.saveNBTFile(nbt, outStream); NBTReflectionUtil.saveNBTFile(nbt, outStream);
} }
public File getFile() { public File getFile() {
return file; return file;
} }
protected Object getCompound() { protected Object getCompound() {
return nbt; return nbt;
} }
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
nbt = compound; nbt = compound;
} }
} }

View File

@ -4,34 +4,34 @@ import org.bukkit.inventory.ItemStack;
public class NBTItem extends NBTCompound { public class NBTItem extends NBTCompound {
private ItemStack bukkitItem; private ItemStack bukkitItem;
public NBTItem(ItemStack item) { public NBTItem(ItemStack item) {
bukkitItem = item.clone(); bukkitItem = item.clone();
} }
public static NBTContainer convertItemtoNBT(ItemStack item) { public static NBTContainer convertItemtoNBT(ItemStack item) {
return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item));
} }
public static ItemStack convertNBTtoItem(NBTCompound comp) { public static ItemStack convertNBTtoItem(NBTCompound comp) {
return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
} }
protected Object getCompound() { protected Object getCompound() {
return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem));
} }
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem)));
} }
public ItemStack getItem() { public ItemStack getItem() {
return bukkitItem; return bukkitItem;
} }
protected void setItem(ItemStack item) { protected void setItem(ItemStack item) {
bukkitItem = item; bukkitItem = item;
} }
} }

View File

@ -6,120 +6,120 @@ import java.lang.reflect.Method;
public class NBTList { public class NBTList {
private String listName; private String listName;
private NBTCompound parent; private NBTCompound parent;
private NBTType type; private NBTType type;
private Object listObject; private Object listObject;
protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { protected NBTList(NBTCompound owner, String name, NBTType type, Object list) {
parent = owner; parent = owner;
listName = name; listName = name;
this.type = type; this.type = type;
this.listObject = list; this.listObject = list;
if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) {
System.err.println("List types != String/Compound are currently not implemented!"); System.err.println("List types != String/Compound are currently not implemented!");
} }
} }
protected void save() { protected void save() {
parent.set(listName, listObject); parent.set(listName, listObject);
} }
public NBTListCompound addCompound() { public NBTListCompound addCompound() {
if (type != NBTType.NBTTagCompound) { if (type != NBTType.NBTTagCompound) {
new Throwable("Using Compound method on a non Compound list!").printStackTrace(); new Throwable("Using Compound method on a non Compound list!").printStackTrace();
return null; return null;
} }
try { try {
Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase());
Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance();
method.invoke(listObject, compound); method.invoke(listObject, compound);
return new NBTListCompound(this, compound); return new NBTListCompound(this, compound);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return null; return null;
} }
public NBTListCompound getCompound(int id) { public NBTListCompound getCompound(int id) {
if (type != NBTType.NBTTagCompound) { if (type != NBTType.NBTTagCompound) {
new Throwable("Using Compound method on a non Compound list!").printStackTrace(); new Throwable("Using Compound method on a non Compound list!").printStackTrace();
return null; return null;
} }
try { try {
Method method = listObject.getClass().getMethod("get", int.class); Method method = listObject.getClass().getMethod("get", int.class);
Object compound = method.invoke(listObject, id); Object compound = method.invoke(listObject, id);
return new NBTListCompound(this, compound); return new NBTListCompound(this, compound);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return null; return null;
} }
public String getString(int i) { public String getString(int i) {
if (type != NBTType.NBTTagString) { if (type != NBTType.NBTTagString) {
new Throwable("Using String method on a non String list!").printStackTrace(); new Throwable("Using String method on a non String list!").printStackTrace();
return null; return null;
} }
try { try {
Method method = listObject.getClass().getMethod("getString", int.class); Method method = listObject.getClass().getMethod("getString", int.class);
return (String) method.invoke(listObject, i); return (String) method.invoke(listObject, i);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return null; return null;
} }
public void addString(String s) { public void addString(String s) {
if (type != NBTType.NBTTagString) { if (type != NBTType.NBTTagString) {
new Throwable("Using String method on a non String list!").printStackTrace(); new Throwable("Using String method on a non String list!").printStackTrace();
return; return;
} }
try { try {
Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase());
method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s));
save(); save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public void setString(int i, String s) { public void setString(int i, String s) {
if (type != NBTType.NBTTagString) { if (type != NBTType.NBTTagString) {
new Throwable("Using String method on a non String list!").printStackTrace(); new Throwable("Using String method on a non String list!").printStackTrace();
return; return;
} }
try { try {
Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase());
method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s));
save(); save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public void remove(int i) { public void remove(int i) {
try { try {
Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class);
method.invoke(listObject, i); method.invoke(listObject, i);
save(); save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public int size() { public int size() {
try { try {
Method method = listObject.getClass().getMethod("size"); Method method = listObject.getClass().getMethod("size");
return (int) method.invoke(listObject); return (int) method.invoke(listObject);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return -1; return -1;
} }
public NBTType getType() { public NBTType getType() {
return type; return type;
} }
} }

View File

@ -5,98 +5,98 @@ import java.util.Set;
public class NBTListCompound { public class NBTListCompound {
private NBTList owner; private NBTList owner;
private Object compound; private Object compound;
protected NBTListCompound(NBTList parent, Object obj) { protected NBTListCompound(NBTList parent, Object obj) {
owner = parent; owner = parent;
compound = obj; compound = obj;
} }
public void setString(String key, String value) { public void setString(String key, String value) {
if (value == null) { if (value == null) {
remove(key); remove(key);
return; return;
} }
try { try {
compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public void setInteger(String key, int value) { public void setInteger(String key, int value) {
try { try {
compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public int getInteger(String value) { public int getInteger(String value) {
try { try {
return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return 0; return 0;
} }
public void setDouble(String key, double value) { public void setDouble(String key, double value) {
try { try {
compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value);
owner.save(); owner.save();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
public double getDouble(String key) { public double getDouble(String key) {
try { try {
return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return 0; return 0;
} }
public String getString(String key) { public String getString(String key) {
try { try {
return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return ""; return "";
} }
public boolean hasKey(String key) { public boolean hasKey(String key) {
try { try {
return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return false; return false;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<String> getKeys() { public Set<String> getKeys() {
try { try {
return (Set<String>) compound.getClass().getMethod("c").invoke(compound); return (Set<String>) compound.getClass().getMethod("c").invoke(compound);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
return new HashSet<>(); return new HashSet<>();
} }
public void remove(String key) { public void remove(String key) {
try { try {
compound.getClass().getMethod("remove", String.class).invoke(compound, key); compound.getClass().getMethod("remove", String.class).invoke(compound, key);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
} }

View File

@ -4,18 +4,18 @@ import org.bukkit.block.BlockState;
public class NBTTileEntity extends NBTCompound { public class NBTTileEntity extends NBTCompound {
private final BlockState tile; private final BlockState tile;
public NBTTileEntity(BlockState tile) { public NBTTileEntity(BlockState tile) {
this.tile = tile; this.tile = tile;
} }
protected Object getCompound() { protected Object getCompound() {
return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); return NBTReflectionUtil.getTileEntityNBTTagCompound(tile);
} }
protected void setCompound(Object compound) { protected void setCompound(Object compound) {
NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound);
} }
} }

View File

@ -1,34 +1,34 @@
package com.massivecraft.factions.zcore.nbtapi; package com.massivecraft.factions.zcore.nbtapi;
public enum NBTType { public enum NBTType {
NBTTagEnd(0), NBTTagEnd(0),
NBTTagByte(1), NBTTagByte(1),
NBTTagShort(2), NBTTagShort(2),
NBTTagInt(3), NBTTagInt(3),
NBTTagLong(4), NBTTagLong(4),
NBTTagFloat(5), NBTTagFloat(5),
NBTTagDouble(6), NBTTagDouble(6),
NBTTagByteArray(7), NBTTagByteArray(7),
NBTTagIntArray(11), NBTTagIntArray(11),
NBTTagString(8), NBTTagString(8),
NBTTagList(9), NBTTagList(9),
NBTTagCompound(10); NBTTagCompound(10);
private final int id; private final int id;
NBTType(int i) { NBTType(int i) {
id = i; id = i;
} }
public static NBTType valueOf(int id) { public static NBTType valueOf(int id) {
for (NBTType t : values()) for (NBTType t : values())
if (t.getId() == id) if (t.getId() == id)
return t; return t;
return NBTType.NBTTagEnd; return NBTType.NBTTagEnd;
} }
public int getId() { public int getId() {
return id; return id;
} }
} }

View File

@ -4,24 +4,24 @@ import com.google.gson.Gson;
public class GsonWrapper { public class GsonWrapper {
private static final Gson gson = new Gson(); private static final Gson gson = new Gson();
public static String getString(Object obj) { public static String getString(Object obj) {
return gson.toJson(obj); return gson.toJson(obj);
} }
public static <T> T deserializeJson(String json, Class<T> type) { public static <T> T deserializeJson(String json, Class<T> type) {
try { try {
if (json == null) { if (json == null) {
return null; return null;
} }
T obj = gson.fromJson(json, type); T obj = gson.fromJson(json, type);
return type.cast(obj); return type.cast(obj);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
return null; return null;
} }
} }
} }

View File

@ -2,25 +2,25 @@ package com.massivecraft.factions.zcore.nbtapi.utils;
public class MethodNames { public class MethodNames {
private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion(); private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion();
public static String getTileDataMethodName() { public static String getTileDataMethodName() {
return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save"; return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save";
} }
public static String getTypeMethodName() { public static String getTypeMethodName() {
return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d"; return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d";
} }
public static String getEntityNbtGetterMethodName() { public static String getEntityNbtGetterMethodName() {
return "b"; return "b";
} }
public static String getEntityNbtSetterMethodName() { public static String getEntityNbtSetterMethodName() {
return "a"; return "a";
} }
public static String getRemoveMethodName() { public static String getRemoveMethodName() {
return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove"; return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove";
} }
} }

View File

@ -3,58 +3,58 @@ package com.massivecraft.factions.zcore.nbtapi.utils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
public enum MinecraftVersion { public enum MinecraftVersion {
Unknown(0), Unknown(0),
MC1_7_R4(174), MC1_7_R4(174),
MC1_8_R3(183), MC1_8_R3(183),
MC1_9_R1(191), MC1_9_R1(191),
MC1_9_R2(192), MC1_9_R2(192),
MC1_10_R1(1101), MC1_10_R1(1101),
MC1_11_R1(1111), MC1_11_R1(1111),
MC1_12_R1(1121); MC1_12_R1(1121);
private static MinecraftVersion version; private static MinecraftVersion version;
private static Boolean hasGsonSupport; private static Boolean hasGsonSupport;
private final int versionId; private final int versionId;
MinecraftVersion(int versionId) { MinecraftVersion(int versionId) {
this.versionId = versionId; this.versionId = versionId;
} }
public static MinecraftVersion getVersion() { public static MinecraftVersion getVersion() {
if (version == null) { if (version == null) {
final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support"); System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support");
try { try {
version = MinecraftVersion.valueOf(ver.replace("v", "MC")); version = MinecraftVersion.valueOf(ver.replace("v", "MC"));
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
version = MinecraftVersion.Unknown; version = MinecraftVersion.Unknown;
} }
if (version != Unknown) { if (version != Unknown) {
System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!");
} else { } else {
System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!"); System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!");
} }
} }
return version; return version;
} }
public static boolean hasGsonSupport() { public static boolean hasGsonSupport() {
if (hasGsonSupport == null) { if (hasGsonSupport == null) {
try { try {
System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson"));
hasGsonSupport = true; hasGsonSupport = true;
} catch (Exception ex) { } catch (Exception ex) {
hasGsonSupport = false; hasGsonSupport = false;
} }
} }
return hasGsonSupport; return hasGsonSupport;
} }
public int getVersionId() { public int getVersionId() {
return versionId; return versionId;
} }
} }

View File

@ -19,367 +19,367 @@ import java.util.Map.Entry;
public abstract class MemoryBoard extends Board { public abstract class MemoryBoard extends Board {
public MemoryBoardMap flocationIds = new MemoryBoardMap(); public MemoryBoardMap flocationIds = new MemoryBoardMap();
//----------------------------------------------// //----------------------------------------------//
// Get and Set // Get and Set
//----------------------------------------------// //----------------------------------------------//
public String getIdAt(FLocation flocation) { public String getIdAt(FLocation flocation) {
if (!flocationIds.containsKey(flocation)) { if (!flocationIds.containsKey(flocation)) {
return "0"; return "0";
} }
return flocationIds.get(flocation); return flocationIds.get(flocation);
} }
public Faction getFactionAt(FLocation flocation) { public Faction getFactionAt(FLocation flocation) {
return Factions.getInstance().getFactionById(getIdAt(flocation)); return Factions.getInstance().getFactionById(getIdAt(flocation));
} }
public void setIdAt(String id, FLocation flocation) { public void setIdAt(String id, FLocation flocation) {
clearOwnershipAt(flocation); clearOwnershipAt(flocation);
if (id.equals("0")) { if (id.equals("0")) {
removeAt(flocation); removeAt(flocation);
} }
flocationIds.put(flocation, id); flocationIds.put(flocation, id);
} }
public void setFactionAt(Faction faction, FLocation flocation) { public void setFactionAt(Faction faction, FLocation flocation) {
setIdAt(faction.getId(), flocation); setIdAt(faction.getId(), flocation);
} }
public void removeAt(FLocation flocation) { public void removeAt(FLocation flocation) {
Faction faction = getFactionAt(flocation); Faction faction = getFactionAt(flocation);
faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation())); faction.getWarps().values().removeIf(lazyLocation -> flocation.isInChunk(lazyLocation.getLocation()));
clearOwnershipAt(flocation); clearOwnershipAt(flocation);
flocationIds.remove(flocation); flocationIds.remove(flocation);
} }
public Set<FLocation> getAllClaims(String factionId) { public Set<FLocation> getAllClaims(String factionId) {
Set<FLocation> locs = new HashSet<>(); Set<FLocation> locs = new HashSet<>();
for (Entry<FLocation, String> entry : flocationIds.entrySet()) { for (Entry<FLocation, String> entry : flocationIds.entrySet()) {
if (entry.getValue().equals(factionId)) { if (entry.getValue().equals(factionId)) {
locs.add(entry.getKey()); locs.add(entry.getKey());
} }
} }
return locs; return locs;
} }
public Set<FLocation> getAllClaims(Faction faction) { public Set<FLocation> getAllClaims(Faction faction) {
return getAllClaims(faction.getId()); return getAllClaims(faction.getId());
} }
// not to be confused with claims, ownership referring to further member-specific ownership of a claim // not to be confused with claims, ownership referring to further member-specific ownership of a claim
public void clearOwnershipAt(FLocation flocation) { public void clearOwnershipAt(FLocation flocation) {
Faction faction = getFactionAt(flocation); Faction faction = getFactionAt(flocation);
if (faction != null && faction.isNormal()) { if (faction != null && faction.isNormal()) {
faction.clearClaimOwnership(flocation); faction.clearClaimOwnership(flocation);
} }
} }
public void unclaimAll(String factionId) { public void unclaimAll(String factionId) {
Faction faction = Factions.getInstance().getFactionById(factionId); Faction faction = Factions.getInstance().getFactionById(factionId);
if (faction != null && faction.isNormal()) { if (faction != null && faction.isNormal()) {
faction.clearAllClaimOwnership(); faction.clearAllClaimOwnership();
faction.clearWarps(); faction.clearWarps();
} }
clean(factionId); clean(factionId);
} }
public void unclaimAllInWorld(String factionId, World world) { public void unclaimAllInWorld(String factionId, World world) {
for (FLocation loc : getAllClaims(factionId)) { for (FLocation loc : getAllClaims(factionId)) {
if (loc.getWorldName().equals(world.getName())) { if (loc.getWorldName().equals(world.getName())) {
removeAt(loc); removeAt(loc);
} }
} }
} }
public void clean(String factionId) { public void clean(String factionId) {
flocationIds.removeFaction(factionId); flocationIds.removeFaction(factionId);
} }
// Is this coord NOT completely surrounded by coords claimed by the same faction? // 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? // Simpler: Is there any nearby coord with a faction other than the faction here?
public boolean isBorderLocation(FLocation flocation) { public boolean isBorderLocation(FLocation flocation) {
Faction faction = getFactionAt(flocation); Faction faction = getFactionAt(flocation);
FLocation a = flocation.getRelative(1, 0); FLocation a = flocation.getRelative(1, 0);
FLocation b = flocation.getRelative(-1, 0); FLocation b = flocation.getRelative(-1, 0);
FLocation c = flocation.getRelative(0, 1); FLocation c = flocation.getRelative(0, 1);
FLocation d = flocation.getRelative(0, -1); FLocation d = flocation.getRelative(0, -1);
return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); 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? // Is this coord connected to any coord claimed by the specified faction?
public boolean isConnectedLocation(FLocation flocation, Faction faction) { public boolean isConnectedLocation(FLocation flocation, Faction faction) {
FLocation a = flocation.getRelative(1, 0); FLocation a = flocation.getRelative(1, 0);
FLocation b = flocation.getRelative(-1, 0); FLocation b = flocation.getRelative(-1, 0);
FLocation c = flocation.getRelative(0, 1); FLocation c = flocation.getRelative(0, 1);
FLocation d = flocation.getRelative(0, -1); FLocation d = flocation.getRelative(0, -1);
return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); 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 * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that
* requires a 'buffer' between factions. * requires a 'buffer' between factions.
* *
* @param flocation - center location. * @param flocation - center location.
* @param faction - faction checking for. * @param faction - faction checking for.
* @param radius - chunk radius to check. * @param radius - chunk radius to check.
* @return true if another Faction is within the radius, otherwise false. * @return true if another Faction is within the radius, otherwise false.
*/ */
public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) {
for (int x = -radius; x <= radius; x++) { for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) { for (int z = -radius; z <= radius; z++) {
if (x == 0 && z == 0) { if (x == 0 && z == 0) {
continue; continue;
} }
FLocation relative = flocation.getRelative(x, z); FLocation relative = flocation.getRelative(x, z);
Faction other = getFactionAt(relative); Faction other = getFactionAt(relative);
if (other.isNormal() && other != faction) { if (other.isNormal() && other != faction) {
return true; return true;
} }
} }
} }
return false; return false;
} }
public void clean() { public void clean() {
Iterator<Entry<FLocation, String>> iter = flocationIds.entrySet().iterator(); Iterator<Entry<FLocation, String>> iter = flocationIds.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Entry<FLocation, String> entry = iter.next(); Entry<FLocation, String> entry = iter.next();
if (!Factions.getInstance().isValidFactionId(entry.getValue())) { if (!Factions.getInstance().isValidFactionId(entry.getValue())) {
P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); P.p.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey());
iter.remove(); iter.remove();
} }
} }
} }
//----------------------------------------------// //----------------------------------------------//
// Cleaner. Remove orphaned foreign keys // Cleaner. Remove orphaned foreign keys
//----------------------------------------------// //----------------------------------------------//
public int getFactionCoordCount(String factionId) { public int getFactionCoordCount(String factionId) {
return flocationIds.getOwnedLandCount(factionId); return flocationIds.getOwnedLandCount(factionId);
} }
//----------------------------------------------// //----------------------------------------------//
// Coord count // Coord count
//----------------------------------------------// //----------------------------------------------//
public int getFactionCoordCount(Faction faction) { public int getFactionCoordCount(Faction faction) {
return getFactionCoordCount(faction.getId()); return getFactionCoordCount(faction.getId());
} }
public int getFactionCoordCountInWorld(Faction faction, String worldName) { public int getFactionCoordCountInWorld(Faction faction, String worldName) {
String factionId = faction.getId(); String factionId = faction.getId();
int ret = 0; int ret = 0;
for (Entry<FLocation, String> entry : flocationIds.entrySet()) { for (Entry<FLocation, String> entry : flocationIds.entrySet()) {
if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) {
ret += 1; ret += 1;
} }
} }
return ret; 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 * 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 * of decreasing z
*/ */
public ArrayList<FancyMessage> getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { public ArrayList<FancyMessage> getMap(FPlayer fplayer, FLocation flocation, double inDegrees) {
Faction faction = fplayer.getFaction(); Faction faction = fplayer.getFaction();
ArrayList<FancyMessage> ret = new ArrayList<>(); ArrayList<FancyMessage> ret = new ArrayList<>();
Faction factionLoc = getFactionAt(flocation); Faction factionLoc = getFactionAt(flocation);
ret.add(new FancyMessage(ChatColor.DARK_GRAY + P.p.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); 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); int buffer = P.p.getConfig().getInt("world-border.buffer", 0);
// Get the compass // Get the compass
ArrayList<String> asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, P.p.txt.parse("<gray>")); ArrayList<String> asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, P.p.txt.parse("<gray>"));
int halfWidth = Conf.mapWidth / 2; int halfWidth = Conf.mapWidth / 2;
// Use player's value for height // Use player's value for height
int halfHeight = fplayer.getMapHeight() / 2; int halfHeight = fplayer.getMapHeight() / 2;
FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight);
int width = halfWidth * 2 + 1; int width = halfWidth * 2 + 1;
int height = halfHeight * 2 + 1; int height = halfHeight * 2 + 1;
if (Conf.showMapFactionKey) { if (Conf.showMapFactionKey) {
height--; height--;
} }
Map<String, Character> fList = new HashMap<>(); Map<String, Character> fList = new HashMap<>();
int chrIdx = 0; int chrIdx = 0;
// For each row // For each row
for (int dz = 0; dz < height; dz++) { for (int dz = 0; dz < height; dz++) {
// Draw and add that row // Draw and add that row
FancyMessage row = new FancyMessage(""); FancyMessage row = new FancyMessage("");
if (dz < 3) { if (dz < 3) {
row.then(asciiCompass.get(dz)); row.then(asciiCompass.get(dz));
} }
for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) {
if (dx == halfWidth && dz == halfHeight) { if (dx == halfWidth && dz == halfHeight) {
row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString()); row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString());
} else { } else {
FLocation flocationHere = topLeft.getRelative(dx, dz); FLocation flocationHere = topLeft.getRelative(dx, dz);
Faction factionHere = getFactionAt(flocationHere); Faction factionHere = getFactionAt(flocationHere);
Relation relation = fplayer.getRelationTo(factionHere); Relation relation = fplayer.getRelationTo(factionHere);
if (flocationHere.isOutsideWorldBorder(buffer)) { if (flocationHere.isOutsideWorldBorder(buffer)) {
row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString());
} else if (factionHere.isWilderness()) { } else if (factionHere.isWilderness()) {
row.then("-").color(Conf.colorWilderness); row.then("-").color(Conf.colorWilderness);
// Lol someone didnt add the x and z making it claim the wrong position Can i copyright this xD // 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)) { if (fplayer.getPlayer().hasPermission(Permission.CLAIMAT.node)) {
row.tooltip(TL.CLAIM_CLICK_TO_CLAIM.format(dx + topLeft.getX(), dz + topLeft.getZ())) 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())); .command(String.format("/f claimat %s %d %d", flocation.getWorldName(), dx + topLeft.getX(), dz + topLeft.getZ()));
} }
} else if (factionHere.isSafeZone()) { } else if (factionHere.isSafeZone()) {
row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer)); row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer));
} else if (factionHere.isWarZone()) { } else if (factionHere.isWarZone()) {
row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer)); row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer));
} else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) ||
(Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) ||
(Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) || (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) ||
(Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) { (Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) {
if (!fList.containsKey(factionHere.getTag())) { if (!fList.containsKey(factionHere.getTag())) {
fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]); fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]);
} }
char tag = fList.get(factionHere.getTag()); char tag = fList.get(factionHere.getTag());
//row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer)); //row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer));
//changed out with a performance friendly one line tooltip :D //changed out with a performance friendly one line tooltip :D
row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer)); row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer));
} else { } else {
row.then("-").color(ChatColor.GRAY); row.then("-").color(ChatColor.GRAY);
} }
} }
} }
ret.add(row); ret.add(row);
} }
// Add the faction key // Add the faction key
if (Conf.showMapFactionKey) { if (Conf.showMapFactionKey) {
FancyMessage fRow = new FancyMessage(""); FancyMessage fRow = new FancyMessage("");
for (String key : fList.keySet()) { for (String key : fList.keySet()) {
fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY); fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY);
} }
ret.add(fRow); ret.add(fRow);
} }
return ret; return ret;
} }
//----------------------------------------------// //----------------------------------------------//
// Map generation // Map generation
//----------------------------------------------// //----------------------------------------------//
private List<String> oneLineToolTip(Faction faction, FPlayer to) { private List<String> oneLineToolTip(Faction faction, FPlayer to) {
return Arrays.asList(faction.describeTo(to)); return Arrays.asList(faction.describeTo(to));
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private List<String> getToolTip(Faction faction, FPlayer to) { private List<String> getToolTip(Faction faction, FPlayer to) {
List<String> ret = new ArrayList<>(); List<String> ret = new ArrayList<>();
List<String> show = P.p.getConfig().getStringList("map"); List<String> show = P.p.getConfig().getStringList("map");
if (!faction.isNormal()) { if (!faction.isNormal()) {
String tag = faction.getTag(to); String tag = faction.getTag(to);
// send header and that's all // send header and that's all
String header = show.get(0); String header = show.get(0);
if (TagReplacer.HEADER.contains(header)) { if (TagReplacer.HEADER.contains(header)) {
ret.add(P.p.txt.titleize(tag)); ret.add(P.p.txt.titleize(tag));
} else { } else {
ret.add(P.p.txt.parse(TagReplacer.FACTION.replace(header, tag))); ret.add(P.p.txt.parse(TagReplacer.FACTION.replace(header, tag)));
} }
return ret; // we only show header for non-normal factions return ret; // we only show header for non-normal factions
} }
for (String raw : show) { for (String raw : show) {
// Hack to get rid of the extra underscores in title normally used to center tag // Hack to get rid of the extra underscores in title normally used to center tag
if (raw.contains("{header}")) { if (raw.contains("{header}")) {
raw = raw.replace("{header}", faction.getTag(to)); raw = raw.replace("{header}", faction.getTag(to));
} }
String parsed = TagUtil.parsePlain(faction, to, raw); // use relations String parsed = TagUtil.parsePlain(faction, to, raw); // use relations
if (parsed == null) { if (parsed == null) {
continue; // Due to minimal f show. continue; // Due to minimal f show.
} }
if (TagUtil.hasFancy(parsed)) { if (TagUtil.hasFancy(parsed)) {
List<FancyMessage> fancy = TagUtil.parseFancy(faction, to, parsed); List<FancyMessage> fancy = TagUtil.parseFancy(faction, to, parsed);
if (fancy != null) { if (fancy != null) {
for (FancyMessage msg : fancy) { for (FancyMessage msg : fancy) {
ret.add((P.p.txt.parse(msg.toOldMessageFormat()))); ret.add((P.p.txt.parse(msg.toOldMessageFormat())));
} }
} }
continue; continue;
} }
if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) {
if (parsed.contains("{ig}")) { if (parsed.contains("{ig}")) {
// replaces all variables with no home TL // replaces all variables with no home TL
parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString();
} }
if (parsed.contains("%")) { if (parsed.contains("%")) {
parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it.
} }
ret.add(P.p.txt.parse(parsed)); 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<FLocation, String> { public class MemoryBoardMap extends HashMap<FLocation, String> {
private static final long serialVersionUID = -6689617828610585368L; private static final long serialVersionUID = -6689617828610585368L;
Multimap<String, FLocation> factionToLandMap = HashMultimap.create(); Multimap<String, FLocation> factionToLandMap = HashMultimap.create();
@Override @Override
public String put(FLocation floc, String factionId) { public String put(FLocation floc, String factionId) {
String previousValue = super.put(floc, factionId); String previousValue = super.put(floc, factionId);
if (previousValue != null) { if (previousValue != null) {
factionToLandMap.remove(previousValue, floc); factionToLandMap.remove(previousValue, floc);
} }
factionToLandMap.put(factionId, floc); factionToLandMap.put(factionId, floc);
return previousValue; return previousValue;
} }
@Override @Override
public String remove(Object key) { public String remove(Object key) {
String result = super.remove(key); String result = super.remove(key);
if (result != null) { if (result != null) {
FLocation floc = (FLocation) key; FLocation floc = (FLocation) key;
factionToLandMap.remove(result, floc); factionToLandMap.remove(result, floc);
} }
return result; return result;
} }
@Override @Override
public void clear() { public void clear() {
super.clear(); super.clear();
factionToLandMap.clear(); factionToLandMap.clear();
} }
public int getOwnedLandCount(String factionId) { public int getOwnedLandCount(String factionId) {
return factionToLandMap.get(factionId).size(); return factionToLandMap.get(factionId).size();
} }
public void removeFaction(String factionId) { public void removeFaction(String factionId) {
Collection<FLocation> flocations = factionToLandMap.removeAll(factionId); Collection<FLocation> flocations = factionToLandMap.removeAll(factionId);
for (FLocation floc : flocations) { for (FLocation floc : flocations) {
super.remove(floc); super.remove(floc);
} }
} }
} }
} }

View File

@ -12,55 +12,55 @@ import java.util.*;
import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListMap;
public abstract class MemoryFPlayers extends FPlayers { public abstract class MemoryFPlayers extends FPlayers {
public Map<String, FPlayer> fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); public Map<String, FPlayer> fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
public void clean() { public void clean() {
for (FPlayer fplayer : this.fPlayers.values()) { for (FPlayer fplayer : this.fPlayers.values()) {
if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) {
P.p.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); P.p.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName());
fplayer.resetFactionData(false); fplayer.resetFactionData(false);
} }
} }
} }
public Collection<FPlayer> getOnlinePlayers() { public Collection<FPlayer> getOnlinePlayers() {
Set<FPlayer> entities = new HashSet<>(); Set<FPlayer> entities = new HashSet<>();
for (Player player : Bukkit.getServer().getOnlinePlayers()) { for (Player player : Bukkit.getServer().getOnlinePlayers()) {
entities.add(this.getByPlayer(player)); entities.add(this.getByPlayer(player));
} }
return entities; return entities;
} }
@Override @Override
public FPlayer getByPlayer(Player player) { public FPlayer getByPlayer(Player player) {
return getById(player.getUniqueId().toString()); return getById(player.getUniqueId().toString());
} }
@Override @Override
public List<FPlayer> getAllFPlayers() { public List<FPlayer> getAllFPlayers() {
return new ArrayList<>(fPlayers.values()); return new ArrayList<>(fPlayers.values());
} }
@Override @Override
public abstract void forceSave(); public abstract void forceSave();
public abstract void load(); public abstract void load();
@Override @Override
public FPlayer getByOfflinePlayer(OfflinePlayer player) { public FPlayer getByOfflinePlayer(OfflinePlayer player) {
return getById(player.getUniqueId().toString()); return getById(player.getUniqueId().toString());
} }
@Override @Override
public FPlayer getById(String id) { public FPlayer getById(String id) {
FPlayer player = fPlayers.get(id); FPlayer player = fPlayers.get(id);
if (player == null) { if (player == null) {
player = generateFPlayer(id); player = generateFPlayer(id);
} }
return player; 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);
} }

View File

@ -1276,7 +1276,8 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) {
// in own faction, with sufficient role or permission to bypass // in own faction, with sufficient role or permission to bypass
// ownership? // 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 // make sure claimOwnership is initialized
if (claimOwnership.isEmpty()) return true; if (claimOwnership.isEmpty()) return true;
@ -1309,5 +1310,7 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
} }
} }
public Set<FLocation> getAllClaims() { return Board.getInstance().getAllClaims(this); } public Set<FLocation> getAllClaims() {
return Board.getInstance().getAllClaims(this);
}
} }

View File

@ -13,164 +13,164 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public abstract class MemoryFactions extends Factions { public abstract class MemoryFactions extends Factions {
public final Map<String, Faction> factions = new ConcurrentHashMap<>(); public final Map<String, Faction> factions = new ConcurrentHashMap<>();
public int nextId = 1; public int nextId = 1;
public void load() { public void load() {
// Make sure the default neutral faction exists // Make sure the default neutral faction exists
if (!factions.containsKey("0")) { if (!factions.containsKey("0")) {
Faction faction = generateFactionObject("0"); Faction faction = generateFactionObject("0");
factions.put("0", faction); factions.put("0", faction);
faction.setTag(TL.WILDERNESS.toString()); faction.setTag(TL.WILDERNESS.toString());
faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString());
} else { } else {
Faction faction = factions.get("0"); Faction faction = factions.get("0");
if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) {
faction.setTag(TL.WILDERNESS.toString()); faction.setTag(TL.WILDERNESS.toString());
} }
if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) {
faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString());
} }
} }
// Make sure the safe zone faction exists // Make sure the safe zone faction exists
if (!factions.containsKey("-1")) { if (!factions.containsKey("-1")) {
Faction faction = generateFactionObject("-1"); Faction faction = generateFactionObject("-1");
factions.put("-1", faction); factions.put("-1", faction);
faction.setTag(TL.SAFEZONE.toString()); faction.setTag(TL.SAFEZONE.toString());
faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString());
} else { } else {
Faction faction = factions.get("-1"); Faction faction = factions.get("-1");
if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) {
faction.setTag(TL.SAFEZONE.toString()); faction.setTag(TL.SAFEZONE.toString());
} }
if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) {
faction.setDescription(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 SafeZone has old pre-1.6.0 name, rename it to remove troublesome " "
if (faction.getTag().contains(" ")) { if (faction.getTag().contains(" ")) {
faction.setTag(TL.SAFEZONE.toString()); faction.setTag(TL.SAFEZONE.toString());
} }
} }
// Make sure the war zone faction exists // Make sure the war zone faction exists
if (!factions.containsKey("-2")) { if (!factions.containsKey("-2")) {
Faction faction = generateFactionObject("-2"); Faction faction = generateFactionObject("-2");
factions.put("-2", faction); factions.put("-2", faction);
faction.setTag(TL.WARZONE.toString()); faction.setTag(TL.WARZONE.toString());
faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); faction.setDescription(TL.WARZONE_DESCRIPTION.toString());
} else { } else {
Faction faction = factions.get("-2"); Faction faction = factions.get("-2");
if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) {
faction.setTag(TL.WARZONE.toString()); faction.setTag(TL.WARZONE.toString());
} }
if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) {
faction.setDescription(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 WarZone has old pre-1.6.0 name, rename it to remove troublesome " "
if (faction.getTag().contains(" ")) { if (faction.getTag().contains(" ")) {
faction.setTag(TL.WARZONE.toString()); faction.setTag(TL.WARZONE.toString());
} }
} }
} }
public Faction getFactionById(String id) { public Faction getFactionById(String id) {
return factions.get(id); return factions.get(id);
} }
public abstract Faction generateFactionObject(String string); public abstract Faction generateFactionObject(String string);
public Faction getByTag(String str) { public Faction getByTag(String str) {
String compStr = MiscUtil.getComparisonString(str); String compStr = MiscUtil.getComparisonString(str);
for (Faction faction : factions.values()) { for (Faction faction : factions.values()) {
if (faction.getComparisonTag().equals(compStr)) { if (faction.getComparisonTag().equals(compStr)) {
return faction; return faction;
} }
} }
return null; return null;
} }
public Faction getBestTagMatch(String start) { public Faction getBestTagMatch(String start) {
int best = 0; int best = 0;
start = start.toLowerCase(); start = start.toLowerCase();
int minlength = start.length(); int minlength = start.length();
Faction bestMatch = null; Faction bestMatch = null;
for (Faction faction : factions.values()) { for (Faction faction : factions.values()) {
String candidate = faction.getTag(); String candidate = faction.getTag();
candidate = ChatColor.stripColor(candidate); candidate = ChatColor.stripColor(candidate);
if (candidate.length() < minlength) { if (candidate.length() < minlength) {
continue; continue;
} }
if (!candidate.toLowerCase().startsWith(start)) { if (!candidate.toLowerCase().startsWith(start)) {
continue; continue;
} }
// The closer to zero the better // The closer to zero the better
int lendiff = candidate.length() - minlength; int lendiff = candidate.length() - minlength;
if (lendiff == 0) { if (lendiff == 0) {
return faction; return faction;
} }
if (lendiff < best || best == 0) { if (lendiff < best || best == 0) {
best = lendiff; best = lendiff;
bestMatch = faction; bestMatch = faction;
} }
} }
return bestMatch; return bestMatch;
} }
public boolean isTagTaken(String str) { public boolean isTagTaken(String str) {
return this.getByTag(str) != null; return this.getByTag(str) != null;
} }
public boolean isValidFactionId(String id) { public boolean isValidFactionId(String id) {
return factions.containsKey(id); return factions.containsKey(id);
} }
public Faction createFaction() { public Faction createFaction() {
Faction faction = generateFactionObject(); Faction faction = generateFactionObject();
factions.put(faction.getId(), faction); factions.put(faction.getId(), faction);
return faction; return faction;
} }
public Set<String> getFactionTags() { public Set<String> getFactionTags() {
Set<String> tags = new HashSet<>(); Set<String> tags = new HashSet<>();
for (Faction faction : factions.values()) { for (Faction faction : factions.values()) {
tags.add(faction.getTag()); tags.add(faction.getTag());
} }
return tags; return tags;
} }
public abstract Faction generateFactionObject(); public abstract Faction generateFactionObject();
public void removeFaction(String id) { public void removeFaction(String id) {
factions.remove(id).remove(); factions.remove(id).remove();
} }
@Override @Override
public ArrayList<Faction> getAllFactions() { public ArrayList<Faction> getAllFactions() {
return new ArrayList<>(factions.values()); return new ArrayList<>(factions.values());
} }
@Override @Override
public Faction getNone() { public Faction getNone() {
return factions.get("0"); return factions.get("0");
} }
@Override @Override
public Faction getWilderness() { public Faction getWilderness() {
return factions.get("0"); return factions.get("0");
} }
@Override @Override
public Faction getSafeZone() { public Faction getSafeZone() {
return factions.get("-1"); return factions.get("-1");
} }
@Override @Override
public Faction getWarZone() { public Faction getWarZone() {
return factions.get("-2"); return factions.get("-2");
} }
public abstract void convertFrom(MemoryFactions old); public abstract void convertFrom(MemoryFactions old);
} }

View File

@ -7,24 +7,24 @@ import com.massivecraft.factions.zcore.MPlugin;
public class SaveTask implements Runnable { public class SaveTask implements Runnable {
private static boolean running = false; private static boolean running = false;
MPlugin p; MPlugin p;
public SaveTask(MPlugin p) { public SaveTask(MPlugin p) {
this.p = p; this.p = p;
} }
public void run() { public void run() {
if (!p.getAutoSave() || running) { if (!p.getAutoSave() || running) {
return; return;
} }
running = true; running = true;
p.preAutoSave(); p.preAutoSave();
Factions.getInstance().forceSave(false); Factions.getInstance().forceSave(false);
FPlayers.getInstance().forceSave(false); FPlayers.getInstance().forceSave(false);
Board.getInstance().forceSave(false); Board.getInstance().forceSave(false);
p.postAutoSave(); p.postAutoSave();
running = false; running = false;
} }
} }

View File

@ -10,36 +10,36 @@ import java.util.logging.Logger;
public class FactionsJSON { public class FactionsJSON {
public static void convertTo() { public static void convertTo() {
if (!(Factions.getInstance() instanceof MemoryFactions)) { if (!(Factions.getInstance() instanceof MemoryFactions)) {
return; return;
} }
if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) { if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) {
return; return;
} }
if (!(Board.getInstance() instanceof MemoryBoard)) { if (!(Board.getInstance() instanceof MemoryBoard)) {
return; return;
} }
new BukkitRunnable() { new BukkitRunnable() {
@Override @Override
public void run() { public void run() {
Logger logger = P.p.getLogger(); Logger logger = P.p.getLogger();
logger.info("Beginning Board conversion to JSON"); logger.info("Beginning Board conversion to JSON");
new JSONBoard().convertFrom((MemoryBoard) Board.getInstance()); new JSONBoard().convertFrom((MemoryBoard) Board.getInstance());
logger.info("Board Converted"); logger.info("Board Converted");
logger.info("Beginning FPlayers conversion to JSON"); logger.info("Beginning FPlayers conversion to JSON");
new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance()); new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance());
logger.info("FPlayers Converted"); logger.info("FPlayers Converted");
logger.info("Beginning Factions conversion to JSON"); logger.info("Beginning Factions conversion to JSON");
new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance()); new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance());
logger.info("Factions Converted"); logger.info("Factions Converted");
logger.info("Refreshing object caches"); logger.info("Refreshing object caches");
for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) {
Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId());
faction.addFPlayer(fPlayer); faction.addFPlayer(fPlayer);
} }
logger.info("Conversion Complete"); logger.info("Conversion Complete");
} }
}.runTaskAsynchronously(P.p); }.runTaskAsynchronously(P.p);
} }
} }

View File

@ -16,88 +16,88 @@ import java.util.TreeMap;
public class JSONBoard extends MemoryBoard { 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<String, Map<String, String>> dumpAsSaveFormat() { public Map<String, Map<String, String>> dumpAsSaveFormat() {
Map<String, Map<String, String>> worldCoordIds = new HashMap<>(); Map<String, Map<String, String>> worldCoordIds = new HashMap<>();
String worldName, coords; String worldName, coords;
String id; String id;
for (Entry<FLocation, String> entry : flocationIds.entrySet()) { for (Entry<FLocation, String> entry : flocationIds.entrySet()) {
worldName = entry.getKey().getWorldName(); worldName = entry.getKey().getWorldName();
coords = entry.getKey().getCoordString(); coords = entry.getKey().getCoordString();
id = entry.getValue(); id = entry.getValue();
if (!worldCoordIds.containsKey(worldName)) { if (!worldCoordIds.containsKey(worldName)) {
worldCoordIds.put(worldName, new TreeMap<String, String>()); worldCoordIds.put(worldName, new TreeMap<String, String>());
} }
worldCoordIds.get(worldName).put(coords, id); worldCoordIds.get(worldName).put(coords, id);
} }
return worldCoordIds; return worldCoordIds;
} }
public void loadFromSaveFormat(Map<String, Map<String, String>> worldCoordIds) { public void loadFromSaveFormat(Map<String, Map<String, String>> worldCoordIds) {
flocationIds.clear(); flocationIds.clear();
String worldName; String worldName;
String[] coords; String[] coords;
int x, z; int x, z;
String factionId; String factionId;
for (Entry<String, Map<String, String>> entry : worldCoordIds.entrySet()) { for (Entry<String, Map<String, String>> entry : worldCoordIds.entrySet()) {
worldName = entry.getKey(); worldName = entry.getKey();
for (Entry<String, String> entry2 : entry.getValue().entrySet()) { for (Entry<String, String> entry2 : entry.getValue().entrySet()) {
coords = entry2.getKey().trim().split("[,\\s]+"); coords = entry2.getKey().trim().split("[,\\s]+");
x = Integer.parseInt(coords[0]); x = Integer.parseInt(coords[0]);
z = Integer.parseInt(coords[1]); z = Integer.parseInt(coords[1]);
factionId = entry2.getValue(); factionId = entry2.getValue();
flocationIds.put(new FLocation(worldName, x, z), factionId); flocationIds.put(new FLocation(worldName, x, z), factionId);
} }
} }
} }
public void forceSave() { public void forceSave() {
forceSave(true); forceSave(true);
} }
public void forceSave(boolean sync) { public void forceSave(boolean sync) {
DiscUtil.writeCatch(file, P.p.gson.toJson(dumpAsSaveFormat()), sync); DiscUtil.writeCatch(file, P.p.gson.toJson(dumpAsSaveFormat()), sync);
} }
public boolean load() { public boolean load() {
P.p.log("Loading board from disk"); P.p.log("Loading board from disk");
if (!file.exists()) { if (!file.exists()) {
P.p.log("No board to load from disk. Creating new file."); P.p.log("No board to load from disk. Creating new file.");
forceSave(); forceSave();
return true; return true;
} }
try { try {
Type type = new TypeToken<Map<String, Map<String, String>>>() { Type type = new TypeToken<Map<String, Map<String, String>>>() {
}.getType(); }.getType();
Map<String, Map<String, String>> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type); Map<String, Map<String, String>> worldCoordIds = P.p.gson.fromJson(DiscUtil.read(file), type);
loadFromSaveFormat(worldCoordIds); loadFromSaveFormat(worldCoordIds);
P.p.log("Loaded " + flocationIds.size() + " board locations"); P.p.log("Loaded " + flocationIds.size() + " board locations");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
P.p.log("Failed to load the board from disk."); P.p.log("Failed to load the board from disk.");
return false; return false;
} }
return true; return true;
} }
@Override @Override
public void convertFrom(MemoryBoard old) { public void convertFrom(MemoryBoard old) {
this.flocationIds = old.flocationIds; this.flocationIds = old.flocationIds;
forceSave(); forceSave();
Board.instance = this; Board.instance = this;
} }
} }

View File

@ -6,20 +6,20 @@ import com.massivecraft.factions.zcore.persist.MemoryFPlayer;
public class JSONFPlayer extends MemoryFPlayer { public class JSONFPlayer extends MemoryFPlayer {
public JSONFPlayer(MemoryFPlayer arg0) { public JSONFPlayer(MemoryFPlayer arg0) {
super(arg0); super(arg0);
} }
public JSONFPlayer(String id) { public JSONFPlayer(String id) {
super(id); super(id);
} }
@Override @Override
public void remove() { public void remove() {
((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId());
} }
public boolean shouldBeSaved() { public boolean shouldBeSaved() {
return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting));
} }
} }

View File

@ -21,170 +21,170 @@ import java.util.Map.Entry;
import java.util.logging.Level; import java.util.logging.Level;
public class JSONFPlayers extends MemoryFPlayers { public class JSONFPlayers extends MemoryFPlayers {
// Info on how to persist // Info on how to persist
private Gson gson; private Gson gson;
private File file; private File file;
public JSONFPlayers() { public JSONFPlayers() {
file = new File(P.p.getDataFolder(), "players.json"); file = new File(P.p.getDataFolder(), "players.json");
gson = P.p.gson; gson = P.p.gson;
} }
public Gson getGson() { public Gson getGson() {
return gson; return gson;
} }
public void setGson(Gson gson) { public void setGson(Gson gson) {
this.gson = gson; this.gson = gson;
} }
public void convertFrom(MemoryFPlayers old) { public void convertFrom(MemoryFPlayers old) {
this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function<FPlayer, JSONFPlayer>() { this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function<FPlayer, JSONFPlayer>() {
@Override @Override
public JSONFPlayer apply(FPlayer arg0) { public JSONFPlayer apply(FPlayer arg0) {
return new JSONFPlayer((MemoryFPlayer) arg0); return new JSONFPlayer((MemoryFPlayer) arg0);
} }
})); }));
forceSave(); forceSave();
FPlayers.instance = this; FPlayers.instance = this;
} }
public void forceSave() { public void forceSave() {
forceSave(true); forceSave(true);
} }
public void forceSave(boolean sync) { public void forceSave(boolean sync) {
final Map<String, JSONFPlayer> entitiesThatShouldBeSaved = new HashMap<>(); final Map<String, JSONFPlayer> entitiesThatShouldBeSaved = new HashMap<>();
for (FPlayer entity : this.fPlayers.values()) { for (FPlayer entity : this.fPlayers.values()) {
if (((MemoryFPlayer) entity).shouldBeSaved()) { if (((MemoryFPlayer) entity).shouldBeSaved()) {
entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity);
} }
} }
saveCore(file, entitiesThatShouldBeSaved, sync); saveCore(file, entitiesThatShouldBeSaved, sync);
} }
private boolean saveCore(File target, Map<String, JSONFPlayer> data, boolean sync) { private boolean saveCore(File target, Map<String, JSONFPlayer> data, boolean sync) {
return DiscUtil.writeCatch(target, this.gson.toJson(data), sync); return DiscUtil.writeCatch(target, this.gson.toJson(data), sync);
} }
public void load() { public void load() {
Map<String, JSONFPlayer> fplayers = this.loadCore(); Map<String, JSONFPlayer> fplayers = this.loadCore();
if (fplayers == null) { if (fplayers == null) {
return; return;
} }
this.fPlayers.clear(); this.fPlayers.clear();
this.fPlayers.putAll(fplayers); this.fPlayers.putAll(fplayers);
P.p.log("Loaded " + fPlayers.size() + " players"); P.p.log("Loaded " + fPlayers.size() + " players");
} }
private Map<String, JSONFPlayer> loadCore() { private Map<String, JSONFPlayer> loadCore() {
if (!this.file.exists()) { if (!this.file.exists()) {
return new HashMap<>(); return new HashMap<>();
} }
String content = DiscUtil.readCatch(this.file); String content = DiscUtil.readCatch(this.file);
if (content == null) { if (content == null) {
return null; return null;
} }
Map<String, JSONFPlayer> data = this.gson.fromJson(content, new TypeToken<Map<String, JSONFPlayer>>() { Map<String, JSONFPlayer> data = this.gson.fromJson(content, new TypeToken<Map<String, JSONFPlayer>>() {
}.getType()); }.getType());
Set<String> list = new HashSet<>(); Set<String> list = new HashSet<>();
Set<String> invalidList = new HashSet<>(); Set<String> invalidList = new HashSet<>();
for (Entry<String, JSONFPlayer> entry : data.entrySet()) { for (Entry<String, JSONFPlayer> entry : data.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
entry.getValue().setId(key); entry.getValue().setId(key);
if (doesKeyNeedMigration(key)) { if (doesKeyNeedMigration(key)) {
if (!isKeyInvalid(key)) { if (!isKeyInvalid(key)) {
list.add(key); list.add(key);
} else { } else {
invalidList.add(key); invalidList.add(key);
} }
} }
} }
if (list.size() > 0) { if (list.size() > 0) {
// We've got some converting to do! // We've got some converting to do!
Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json");
// First we'll make a backup, because god forbid anybody heed a // First we'll make a backup, because god forbid anybody heed a
// warning // warning
File file = new File(this.file.getParentFile(), "players.json.old"); File file = new File(this.file.getParentFile(), "players.json.old");
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
saveCore(file, data, true); saveCore(file, data, true);
Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath());
// Start fetching those UUIDs // 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."); 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)); UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list));
try { try {
Map<String, UUID> response = fetcher.call(); Map<String, UUID> response = fetcher.call();
for (String s : list) { for (String s : list) {
// Are we missing any responses? // Are we missing any responses?
if (!response.containsKey(s)) { if (!response.containsKey(s)) {
// They don't have a UUID so they should just be removed // They don't have a UUID so they should just be removed
invalidList.add(s); invalidList.add(s);
} }
} }
for (String value : response.keySet()) { for (String value : response.keySet()) {
// For all the valid responses, let's replace their old // For all the valid responses, let's replace their old
// named entry with a UUID key // named entry with a UUID key
String id = response.get(value).toString(); String id = response.get(value).toString();
JSONFPlayer player = data.get(value); JSONFPlayer player = data.get(value);
if (player == null) { if (player == null) {
// The player never existed here, and shouldn't persist // The player never existed here, and shouldn't persist
invalidList.add(value); invalidList.add(value);
continue; 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.remove(value); // Out with the old...
data.put(id, player); // And in with the new data.put(id, player); // And in with the new
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if (invalidList.size() > 0) { if (invalidList.size() > 0) {
for (String name : invalidList) { for (String name : invalidList) {
// Remove all the invalid names we collected // Remove all the invalid names we collected
data.remove(name); 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, "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, ", ")); Bukkit.getLogger().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", "));
} }
saveCore(this.file, data, true); // Update the saveCore(this.file, data, true); // Update the
// flatfile // flatfile
Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID.");
} }
return data; return data;
} }
private boolean doesKeyNeedMigration(String key) { 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}")) { 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.. // Not a valid UUID..
// Valid playername, we'll mark this as one for conversion // Valid playername, we'll mark this as one for conversion
// to UUID // to UUID
return key.matches("[a-zA-Z0-9_]{2,16}"); return key.matches("[a-zA-Z0-9_]{2,16}");
} }
return false; return false;
} }
private boolean isKeyInvalid(String key) { private boolean isKeyInvalid(String key) {
return !key.matches("[a-zA-Z0-9_]{2,16}"); return !key.matches("[a-zA-Z0-9_]{2,16}");
} }
@Override @Override
public FPlayer generateFPlayer(String id) { public FPlayer generateFPlayer(String id) {
FPlayer player = new JSONFPlayer(id); FPlayer player = new JSONFPlayer(id);
this.fPlayers.put(player.getId(), player); this.fPlayers.put(player.getId(), player);
return player; return player;
} }
} }

View File

@ -4,15 +4,15 @@ import com.massivecraft.factions.zcore.persist.MemoryFaction;
public class JSONFaction extends MemoryFaction { public class JSONFaction extends MemoryFaction {
public JSONFaction(MemoryFaction arg0) { public JSONFaction(MemoryFaction arg0) {
super(arg0); super(arg0);
} }
public JSONFaction() { public JSONFaction() {
} }
public JSONFaction(String id) { public JSONFaction(String id) {
super(id); super(id);
} }
} }

View File

@ -21,233 +21,233 @@ import java.util.Map.Entry;
import java.util.logging.Level; import java.util.logging.Level;
public class JSONFactions extends MemoryFactions { public class JSONFactions extends MemoryFactions {
// Info on how to persist // Info on how to persist
private final Gson gson; private final Gson gson;
private final File file; private final File file;
public JSONFactions() { public JSONFactions() {
this.file = new File(P.p.getDataFolder(), "factions.json"); this.file = new File(P.p.getDataFolder(), "factions.json");
this.gson = P.p.gson; this.gson = P.p.gson;
this.nextId = 1; this.nextId = 1;
} }
public Gson getGson() { public Gson getGson() {
return gson; return gson;
} }
// -------------------------------------------- // // -------------------------------------------- //
// CONSTRUCTORS // CONSTRUCTORS
// -------------------------------------------- // // -------------------------------------------- //
public File getFile() { public File getFile() {
return file; return file;
} }
public void forceSave() { public void forceSave() {
forceSave(true); forceSave(true);
} }
public void forceSave(boolean sync) { public void forceSave(boolean sync) {
final Map<String, JSONFaction> entitiesThatShouldBeSaved = new HashMap<>(); final Map<String, JSONFaction> entitiesThatShouldBeSaved = new HashMap<>();
for (Faction entity : this.factions.values()) { for (Faction entity : this.factions.values()) {
entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity);
} }
saveCore(file, entitiesThatShouldBeSaved, sync); saveCore(file, entitiesThatShouldBeSaved, sync);
} }
private boolean saveCore(File target, Map<String, JSONFaction> entities, boolean sync) { private boolean saveCore(File target, Map<String, JSONFaction> entities, boolean sync) {
return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync); return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync);
} }
public void load() { public void load() {
Map<String, JSONFaction> factions = this.loadCore(); Map<String, JSONFaction> factions = this.loadCore();
if (factions == null) { if (factions == null) {
return; return;
} }
this.factions.putAll(factions); this.factions.putAll(factions);
super.load(); super.load();
P.p.log("Loaded " + factions.size() + " Factions"); P.p.log("Loaded " + factions.size() + " Factions");
} }
private Map<String, JSONFaction> loadCore() { private Map<String, JSONFaction> loadCore() {
if (!this.file.exists()) { if (!this.file.exists()) {
return new HashMap<>(); return new HashMap<>();
} }
String content = DiscUtil.readCatch(this.file); String content = DiscUtil.readCatch(this.file);
if (content == null) { if (content == null) {
return null; return null;
} }
Map<String, JSONFaction> data = this.gson.fromJson(content, new TypeToken<Map<String, JSONFaction>>() { Map<String, JSONFaction> data = this.gson.fromJson(content, new TypeToken<Map<String, JSONFaction>>() {
}.getType()); }.getType());
this.nextId = 1; this.nextId = 1;
// Do we have any names that need updating in claims or invites? // Do we have any names that need updating in claims or invites?
int needsUpdate = 0; int needsUpdate = 0;
for (Entry<String, JSONFaction> entry : data.entrySet()) { for (Entry<String, JSONFaction> entry : data.entrySet()) {
String id = entry.getKey(); String id = entry.getKey();
Faction f = entry.getValue(); Faction f = entry.getValue();
f.setId(id); f.setId(id);
this.updateNextIdForId(id); this.updateNextIdForId(id);
needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); needsUpdate += whichKeysNeedMigration(f.getInvites()).size();
for (Set<String> keys : f.getClaimOwnership().values()) { for (Set<String> keys : f.getClaimOwnership().values()) {
needsUpdate += whichKeysNeedMigration(keys).size(); needsUpdate += whichKeysNeedMigration(keys).size();
} }
} }
if (needsUpdate > 0) { if (needsUpdate > 0) {
// We've got some converting to do! // We've got some converting to do!
Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json"); Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json");
// First we'll make a backup, because god forbid anybody heed a // First we'll make a backup, because god forbid anybody heed a
// warning // warning
File file = new File(this.file.getParentFile(), "factions.json.old"); File file = new File(this.file.getParentFile(), "factions.json.old");
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
saveCore(file, data, true); saveCore(file, data, true);
Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); 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()) { for (String string : data.keySet()) {
Faction f = data.get(string); Faction f = data.get(string);
Map<FLocation, Set<String>> claims = f.getClaimOwnership(); Map<FLocation, Set<String>> claims = f.getClaimOwnership();
for (FLocation key : claims.keySet()) { for (FLocation key : claims.keySet()) {
Set<String> set = claims.get(key); Set<String> set = claims.get(key);
Set<String> list = whichKeysNeedMigration(set); Set<String> list = whichKeysNeedMigration(set);
if (list.size() > 0) { if (list.size() > 0) {
UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list));
try { try {
Map<String, UUID> response = fetcher.call(); Map<String, UUID> response = fetcher.call();
for (String value : response.keySet()) { for (String value : response.keySet()) {
// Let's replace their old named entry with a // Let's replace their old named entry with a
// UUID key // UUID key
String id = response.get(value).toString(); String id = response.get(value).toString();
set.remove(value.toLowerCase()); // Out with the set.remove(value.toLowerCase()); // Out with the
// old... // old...
set.add(id); // And in with the new set.add(id); // And in with the new
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
claims.put(key, set); // Update claims.put(key, set); // Update
} }
} }
} }
// Update invites // Update invites
for (String string : data.keySet()) { for (String string : data.keySet()) {
Faction f = data.get(string); Faction f = data.get(string);
Set<String> invites = f.getInvites(); Set<String> invites = f.getInvites();
Set<String> list = whichKeysNeedMigration(invites); Set<String> list = whichKeysNeedMigration(invites);
if (list.size() > 0) { if (list.size() > 0) {
UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list));
try { try {
Map<String, UUID> response = fetcher.call(); Map<String, UUID> response = fetcher.call();
for (String value : response.keySet()) { for (String value : response.keySet()) {
// Let's replace their old named entry with a UUID // Let's replace their old named entry with a UUID
// key // key
String id = response.get(value).toString(); String id = response.get(value).toString();
invites.remove(value.toLowerCase()); // Out with the invites.remove(value.toLowerCase()); // Out with the
// old... // old...
invites.add(id); // And in with the new invites.add(id); // And in with the new
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
saveCore(this.file, data, true); // Update the flatfile saveCore(this.file, data, true); // Update the flatfile
Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID.");
} }
return data; return data;
} }
private Set<String> whichKeysNeedMigration(Set<String> keys) { private Set<String> whichKeysNeedMigration(Set<String> keys) {
HashSet<String> list = new HashSet<>(); HashSet<String> list = new HashSet<>();
for (String value : keys) { 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}")) { 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.. // Not a valid UUID..
if (value.matches("[a-zA-Z0-9_]{2,16}")) { if (value.matches("[a-zA-Z0-9_]{2,16}")) {
// Valid playername, we'll mark this as one for conversion // Valid playername, we'll mark this as one for conversion
// to UUID // to UUID
list.add(value); list.add(value);
} }
} }
} }
return list; return list;
} }
// -------------------------------------------- // // -------------------------------------------- //
// ID MANAGEMENT // ID MANAGEMENT
// -------------------------------------------- // // -------------------------------------------- //
public String getNextId() { public String getNextId() {
while (!isIdFree(this.nextId)) { while (!isIdFree(this.nextId)) {
this.nextId += 1; this.nextId += 1;
} }
return Integer.toString(this.nextId); return Integer.toString(this.nextId);
} }
public boolean isIdFree(String id) { public boolean isIdFree(String id) {
return !this.factions.containsKey(id); return !this.factions.containsKey(id);
} }
public boolean isIdFree(int id) { public boolean isIdFree(int id) {
return this.isIdFree(Integer.toString(id)); return this.isIdFree(Integer.toString(id));
} }
protected synchronized void updateNextIdForId(int id) { protected synchronized void updateNextIdForId(int id) {
if (this.nextId < id) { if (this.nextId < id) {
this.nextId = id + 1; this.nextId = id + 1;
} }
} }
protected void updateNextIdForId(String id) { protected void updateNextIdForId(String id) {
try { try {
int idAsInt = Integer.parseInt(id); int idAsInt = Integer.parseInt(id);
this.updateNextIdForId(idAsInt); this.updateNextIdForId(idAsInt);
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
@Override @Override
public Faction generateFactionObject() { public Faction generateFactionObject() {
String id = getNextId(); String id = getNextId();
Faction faction = new JSONFaction(id); Faction faction = new JSONFaction(id);
updateNextIdForId(id); updateNextIdForId(id);
return faction; return faction;
} }
@Override @Override
public Faction generateFactionObject(String id) { public Faction generateFactionObject(String id) {
return new JSONFaction(id); return new JSONFaction(id);
} }
@Override @Override
public void convertFrom(MemoryFactions old) { public void convertFrom(MemoryFactions old) {
this.factions.putAll(Maps.transformValues(old.factions, new Function<Faction, JSONFaction>() { this.factions.putAll(Maps.transformValues(old.factions, new Function<Faction, JSONFaction>() {
@Override @Override
public JSONFaction apply(Faction arg0) { public JSONFaction apply(Faction arg0) {
return new JSONFaction((MemoryFaction) arg0); return new JSONFaction((MemoryFaction) arg0);
} }
})); }));
this.nextId = old.nextId; this.nextId = old.nextId;
forceSave(); forceSave();
Factions.instance = this; Factions.instance = this;
} }
} }

View File

@ -12,107 +12,107 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
public class DiscUtil { public class DiscUtil {
// -------------------------------------------- // // -------------------------------------------- //
// CONSTANTS // CONSTANTS
// -------------------------------------------- // // -------------------------------------------- //
private final static String UTF8 = "UTF-8"; private final static String UTF8 = "UTF-8";
// -------------------------------------------- // // -------------------------------------------- //
// BYTE // BYTE
// -------------------------------------------- // // -------------------------------------------- //
private static HashMap<String, Lock> locks = new HashMap<>(); private static HashMap<String, Lock> locks = new HashMap<>();
public static byte[] readBytes(File file) throws IOException { public static byte[] readBytes(File file) throws IOException {
int length = (int) file.length(); int length = (int) file.length();
byte[] output = new byte[length]; byte[] output = new byte[length];
InputStream in = new FileInputStream(file); InputStream in = new FileInputStream(file);
int offset = 0; int offset = 0;
while (offset < length) { while (offset < length) {
offset += in.read(output, offset, (length - offset)); offset += in.read(output, offset, (length - offset));
} }
in.close(); in.close();
return output; return output;
} }
// -------------------------------------------- // // -------------------------------------------- //
// STRING // STRING
// -------------------------------------------- // // -------------------------------------------- //
public static void writeBytes(File file, byte[] bytes) throws IOException { public static void writeBytes(File file, byte[] bytes) throws IOException {
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
out.write(bytes); out.write(bytes);
out.close(); out.close();
} }
public static void write(File file, String content) throws IOException { public static void write(File file, String content) throws IOException {
writeBytes(file, utf8(content)); writeBytes(file, utf8(content));
} }
// -------------------------------------------- // // -------------------------------------------- //
// CATCH // CATCH
// -------------------------------------------- // // -------------------------------------------- //
public static String read(File file) throws IOException { public static String read(File file) throws IOException {
return utf8(readBytes(file)); return utf8(readBytes(file));
} }
public static boolean writeCatch(final File file, final String content, boolean sync) { public static boolean writeCatch(final File file, final String content, boolean sync) {
String name = file.getName(); String name = file.getName();
final Lock lock; final Lock lock;
// Create lock for each file if there isn't already one. // Create lock for each file if there isn't already one.
if (locks.containsKey(name)) { if (locks.containsKey(name)) {
lock = locks.get(name); lock = locks.get(name);
} else { } else {
ReadWriteLock rwl = new ReentrantReadWriteLock(); ReadWriteLock rwl = new ReentrantReadWriteLock();
lock = rwl.writeLock(); lock = rwl.writeLock();
locks.put(name, lock); locks.put(name, lock);
} }
if (sync) { if (sync) {
lock.lock(); lock.lock();
try { try {
write(file, content); write(file, content);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
lock.unlock(); lock.unlock();
} }
} else { } else {
Bukkit.getScheduler().runTaskAsynchronously(P.p, () -> { Bukkit.getScheduler().runTaskAsynchronously(P.p, () -> {
lock.lock(); lock.lock();
try { try {
write(file, content); write(file, content);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
lock.unlock(); 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) { public static String readCatch(File file) {
try { try {
return read(file); return read(file);
} catch (IOException e) { } catch (IOException e) {
return null; return null;
} }
} }
// -------------------------------------------- // // -------------------------------------------- //
// UTF8 ENCODE AND DECODE // UTF8 ENCODE AND DECODE
// -------------------------------------------- // // -------------------------------------------- //
public static byte[] utf8(String string) { public static byte[] utf8(String string) {
return string.getBytes(StandardCharsets.UTF_8); return string.getBytes(StandardCharsets.UTF_8);
} }
public static String utf8(byte[] bytes) { public static String utf8(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8); return new String(bytes, StandardCharsets.UTF_8);
} }
} }

View File

@ -10,65 +10,65 @@ import java.util.Map.Entry;
public class PermUtil { public class PermUtil {
public Map<String, String> permissionDescriptions = new HashMap<>(); public Map<String, String> permissionDescriptions = new HashMap<>();
protected MPlugin p; protected MPlugin p;
public PermUtil(MPlugin p) { public PermUtil(MPlugin p) {
this.p = p; this.p = p;
this.setup(); this.setup();
} }
public String getForbiddenMessage(String perm) { public String getForbiddenMessage(String perm) {
return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm));
} }
/** /**
* This method hooks into all permission plugins we are supporting * This method hooks into all permission plugins we are supporting
*/ */
public final void setup() { public final void setup() {
for (Permission permission : p.getDescription().getPermissions()) { for (Permission permission : p.getDescription().getPermissions()) {
//plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); //plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\"");
this.permissionDescriptions.put(permission.getName(), permission.getDescription()); this.permissionDescriptions.put(permission.getName(), permission.getDescription());
} }
} }
public String getPermissionDescription(String perm) { public String getPermissionDescription(String perm) {
String desc = permissionDescriptions.get(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 * This method tests if me has a certain permission and returns true if me has. Otherwise false
*/ */
public boolean has(CommandSender me, String perm) { public boolean has(CommandSender me, String perm) {
return me != null && me.hasPermission(perm); return me != null && me.hasPermission(perm);
} }
public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { public boolean has(CommandSender me, String perm, boolean informSenderIfNot) {
if (has(me, perm)) { if (has(me, perm)) {
return true; return true;
} else if (informSenderIfNot && me != null) { } else if (informSenderIfNot && me != null) {
me.sendMessage(this.getForbiddenMessage(perm)); me.sendMessage(this.getForbiddenMessage(perm));
} }
return false; return false;
} }
public <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val) { public <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val) {
if (perm2val == null) { if (perm2val == null) {
return null; return null;
} }
T ret = null; T ret = null;
for (Entry<String, T> entry : perm2val.entrySet()) { for (Entry<String, T> entry : perm2val.entrySet()) {
ret = entry.getValue(); ret = entry.getValue();
if (has(me, entry.getKey())) { if (has(me, entry.getKey())) {
break; break;
} }
} }
return ret; return ret;
} }
} }

View File

@ -10,144 +10,144 @@ import java.util.logging.Level;
public class Persist { public class Persist {
private MPlugin p; private MPlugin p;
public Persist(MPlugin p) { public Persist(MPlugin p) {
this.p = 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) { public static String getName(Class<?> clazz) {
return clazz.getSimpleName().toLowerCase(); return clazz.getSimpleName().toLowerCase();
} }
public static String getName(Object o) { public static String getName(Object o) {
return getName(o.getClass()); return getName(o.getClass());
} }
public static String getName(Type type) { public static String getName(Type type) {
return getName(type.getClass()); 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) { public File getFile(String name) {
return new File(p.getDataFolder(), name + ".json"); return new File(p.getDataFolder(), name + ".json");
} }
public File getFile(Class<?> clazz) { public File getFile(Class<?> clazz) {
return getFile(getName(clazz)); return getFile(getName(clazz));
} }
public File getFile(Object obj) { public File getFile(Object obj) {
return getFile(getName(obj)); return getFile(getName(obj));
} }
public File getFile(Type type) { public File getFile(Type type) {
return getFile(getName(type)); return getFile(getName(type));
} }
// NICE WRAPPERS // NICE WRAPPERS
public <T> T loadOrSaveDefault(T def, Class<T> clazz) { public <T> T loadOrSaveDefault(T def, Class<T> clazz) {
return loadOrSaveDefault(def, clazz, getFile(clazz)); return loadOrSaveDefault(def, clazz, getFile(clazz));
} }
public <T> T loadOrSaveDefault(T def, Class<T> clazz, String name) { public <T> T loadOrSaveDefault(T def, Class<T> clazz, String name) {
return loadOrSaveDefault(def, clazz, getFile(name)); return loadOrSaveDefault(def, clazz, getFile(name));
} }
public <T> T loadOrSaveDefault(T def, Class<T> clazz, File file) { public <T> T loadOrSaveDefault(T def, Class<T> clazz, File file) {
if (!file.exists()) { if (!file.exists()) {
p.log("Creating default: " + file); p.log("Creating default: " + file);
this.save(def, file); this.save(def, file);
return def; return def;
} }
T loaded = this.load(clazz, file); T loaded = this.load(clazz, file);
if (loaded == null) { if (loaded == null) {
p.log(Level.WARNING, "Using default as I failed to load: " + file); 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 // backup bad file, so user can attempt to recover their changes from it
File backup = new File(file.getPath() + "_bad"); File backup = new File(file.getPath() + "_bad");
if (backup.exists()) { if (backup.exists()) {
backup.delete(); backup.delete();
} }
p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); p.log(Level.WARNING, "Backing up copy of bad file to: " + backup);
file.renameTo(backup); file.renameTo(backup);
return def; return def;
} }
return loaded; return loaded;
} }
// SAVE // SAVE
public boolean save(Object instance) { public boolean save(Object instance) {
return save(instance, getFile(instance)); return save(instance, getFile(instance));
} }
public boolean save(Object instance, String name) { public boolean save(Object instance, String name) {
return save(instance, getFile(name)); return save(instance, getFile(name));
} }
public boolean save(Object instance, File file) { public boolean save(Object instance, File file) {
return DiscUtil.writeCatch(file, p.gson.toJson(instance), false); return DiscUtil.writeCatch(file, p.gson.toJson(instance), false);
} }
// LOAD BY CLASS // LOAD BY CLASS
public <T> T load(Class<T> clazz) { public <T> T load(Class<T> clazz) {
return load(clazz, getFile(clazz)); return load(clazz, getFile(clazz));
} }
public <T> T load(Class<T> clazz, String name) { public <T> T load(Class<T> clazz, String name) {
return load(clazz, getFile(name)); return load(clazz, getFile(name));
} }
public <T> T load(Class<T> clazz, File file) { public <T> T load(Class<T> clazz, File file) {
String content = DiscUtil.readCatch(file); String content = DiscUtil.readCatch(file);
if (content == null) { if (content == null) {
return null; return null;
} }
try { try {
return p.gson.fromJson(content, clazz); return p.gson.fromJson(content, clazz);
} catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely
p.log(Level.WARNING, ex.getMessage()); p.log(Level.WARNING, ex.getMessage());
} }
return null; return null;
} }
// LOAD BY TYPE // LOAD BY TYPE
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T load(Type typeOfT, String name) { public <T> T load(Type typeOfT, String name) {
return (T) load(typeOfT, getFile(name)); return (T) load(typeOfT, getFile(name));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T load(Type typeOfT, File file) { public <T> T load(Type typeOfT, File file) {
String content = DiscUtil.readCatch(file); String content = DiscUtil.readCatch(file);
if (content == null) { if (content == null) {
return null; return null;
} }
try { try {
return (T) p.gson.fromJson(content, typeOfT); 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 } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely
p.log(Level.WARNING, ex.getMessage()); p.log(Level.WARNING, ex.getMessage());
} }
return null; return null;
} }
} }

View File

@ -24,59 +24,59 @@ import java.util.Random;
public class SmokeUtil { public class SmokeUtil {
public static Random random = new Random(); public static Random random = new Random();
// -------------------------------------------- // // -------------------------------------------- //
// Spawn once // Spawn once
// -------------------------------------------- // // -------------------------------------------- //
// Single ======== // Single ========
public static void spawnSingle(Location location, int direction) { public static void spawnSingle(Location location, int direction) {
if (location == null) { if (location == null) {
return; return;
} }
location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction);
} }
public static void spawnSingle(Location location) { public static void spawnSingle(Location location) {
spawnSingle(location, 4); spawnSingle(location, 4);
} }
public static void spawnSingleRandom(Location location) { public static void spawnSingleRandom(Location location) {
spawnSingle(location, random.nextInt(9)); spawnSingle(location, random.nextInt(9));
} }
// Simple Cloud ======== // Simple Cloud ========
public static void spawnCloudSimple(Location location) { public static void spawnCloudSimple(Location location) {
for (int i = 0; i <= 8; i++) { for (int i = 0; i <= 8; i++) {
spawnSingle(location, i); spawnSingle(location, i);
} }
} }
public static void spawnCloudSimple(Collection<Location> locations) { public static void spawnCloudSimple(Collection<Location> locations) {
for (Location location : locations) { for (Location location : locations) {
spawnCloudSimple(location); spawnCloudSimple(location);
} }
} }
// Random Cloud ======== // Random Cloud ========
public static void spawnCloudRandom(Location location, float thickness) { public static void spawnCloudRandom(Location location, float thickness) {
int singles = (int) Math.floor(thickness * 9); int singles = (int) Math.floor(thickness * 9);
for (int i = 0; i < singles; i++) { for (int i = 0; i < singles; i++) {
spawnSingleRandom(location.clone()); spawnSingleRandom(location.clone());
} }
} }
public static void spawnCloudRandom(Collection<Location> locations, float thickness) { public static void spawnCloudRandom(Collection<Location> locations, float thickness) {
for (Location location : locations) { for (Location location : locations) {
spawnCloudRandom(location, thickness); spawnCloudRandom(location, thickness);
} }
} }
// -------------------------------------------- // // -------------------------------------------- //
// Attach continuous effects to or locations // Attach continuous effects to or locations
// -------------------------------------------- // // -------------------------------------------- //
// TODO // TODO
} }

View File

@ -17,293 +17,293 @@ import java.util.UUID;
*/ */
public enum TagReplacer { public enum TagReplacer {
/** /**
* Fancy variables, used by f show * Fancy variables, used by f show
*/ */
ALLIES_LIST(TagType.FANCY, "{allies-list}"), ALLIES_LIST(TagType.FANCY, "{allies-list}"),
ONLINE_LIST(TagType.FANCY, "{online-list}"), ONLINE_LIST(TagType.FANCY, "{online-list}"),
ENEMIES_LIST(TagType.FANCY, "{enemies-list}"), ENEMIES_LIST(TagType.FANCY, "{enemies-list}"),
TRUCES_LIST(TagType.FANCY, "{truces-list}"), TRUCES_LIST(TagType.FANCY, "{truces-list}"),
OFFLINE_LIST(TagType.FANCY, "{offline-list}"), OFFLINE_LIST(TagType.FANCY, "{offline-list}"),
ALTS(TagType.FANCY, "{alts}"), ALTS(TagType.FANCY, "{alts}"),
/** /**
* Player variables, require a player * Player variables, require a player
*/ */
PLAYER_GROUP(TagType.PLAYER, "{group}"), PLAYER_GROUP(TagType.PLAYER, "{group}"),
LAST_SEEN(TagType.PLAYER, "{lastSeen}"), LAST_SEEN(TagType.PLAYER, "{lastSeen}"),
PLAYER_BALANCE(TagType.PLAYER, "{balance}"), PLAYER_BALANCE(TagType.PLAYER, "{balance}"),
PLAYER_POWER(TagType.PLAYER, "{player-power}"), PLAYER_POWER(TagType.PLAYER, "{player-power}"),
PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"), PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"),
PLAYER_KILLS(TagType.PLAYER, "{player-kills}"), PLAYER_KILLS(TagType.PLAYER, "{player-kills}"),
PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"), PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"),
/** /**
* Faction variables, require at least a player * Faction variables, require at least a player
*/ */
HOME_X(TagType.FACTION, "{x}"), HOME_X(TagType.FACTION, "{x}"),
HOME_Y(TagType.FACTION, "{y}"), HOME_Y(TagType.FACTION, "{y}"),
HOME_Z(TagType.FACTION, "{z}"), HOME_Z(TagType.FACTION, "{z}"),
CHUNKS(TagType.FACTION, "{chunks}"), CHUNKS(TagType.FACTION, "{chunks}"),
WARPS(TagType.FACTION, "{warps}"), WARPS(TagType.FACTION, "{warps}"),
HEADER(TagType.FACTION, "{header}"), HEADER(TagType.FACTION, "{header}"),
POWER(TagType.FACTION, "{power}"), POWER(TagType.FACTION, "{power}"),
MAX_POWER(TagType.FACTION, "{maxPower}"), MAX_POWER(TagType.FACTION, "{maxPower}"),
POWER_BOOST(TagType.FACTION, "{power-boost}"), POWER_BOOST(TagType.FACTION, "{power-boost}"),
LEADER(TagType.FACTION, "{leader}"), LEADER(TagType.FACTION, "{leader}"),
JOINING(TagType.FACTION, "{joining}"), JOINING(TagType.FACTION, "{joining}"),
FACTION(TagType.FACTION, "{faction}"), FACTION(TagType.FACTION, "{faction}"),
PLAYER_NAME(TagType.FACTION, "{name}"), PLAYER_NAME(TagType.FACTION, "{name}"),
HOME_WORLD(TagType.FACTION, "{world}"), HOME_WORLD(TagType.FACTION, "{world}"),
RAIDABLE(TagType.FACTION, "{raidable}"), RAIDABLE(TagType.FACTION, "{raidable}"),
PEACEFUL(TagType.FACTION, "{peaceful}"), PEACEFUL(TagType.FACTION, "{peaceful}"),
PERMANENT(TagType.FACTION, "permanent"), // no braces needed PERMANENT(TagType.FACTION, "permanent"), // no braces needed
TIME_LEFT(TagType.FACTION, "{time-left}"), TIME_LEFT(TagType.FACTION, "{time-left}"),
LAND_VALUE(TagType.FACTION, "{land-value}"), LAND_VALUE(TagType.FACTION, "{land-value}"),
DESCRIPTION(TagType.FACTION, "{description}"), DESCRIPTION(TagType.FACTION, "{description}"),
CREATE_DATE(TagType.FACTION, "{create-date}"), CREATE_DATE(TagType.FACTION, "{create-date}"),
LAND_REFUND(TagType.FACTION, "{land-refund}"), LAND_REFUND(TagType.FACTION, "{land-refund}"),
BANK_BALANCE(TagType.FACTION, "{faction-balance}"), BANK_BALANCE(TagType.FACTION, "{faction-balance}"),
ALLIES_COUNT(TagType.FACTION, "{allies}"), ALLIES_COUNT(TagType.FACTION, "{allies}"),
ENEMIES_COUNT(TagType.FACTION, "{enemies}"), ENEMIES_COUNT(TagType.FACTION, "{enemies}"),
TRUCES_COUNT(TagType.FACTION, "{truces}"), TRUCES_COUNT(TagType.FACTION, "{truces}"),
ONLINE_COUNT(TagType.FACTION, "{online}"), ONLINE_COUNT(TagType.FACTION, "{online}"),
OFFLINE_COUNT(TagType.FACTION, "{offline}"), OFFLINE_COUNT(TagType.FACTION, "{offline}"),
FACTION_SIZE(TagType.FACTION, "{members}"), FACTION_SIZE(TagType.FACTION, "{members}"),
FACTION_KILLS(TagType.FACTION, "{faction-kills}"), FACTION_KILLS(TagType.FACTION, "{faction-kills}"),
FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"), FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"),
FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"), FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"),
FACTION_STRIKES(TagType.FACTION, "{strikes}"), FACTION_STRIKES(TagType.FACTION, "{strikes}"),
FACTION_POINTS(TagType.FACTION, "{faction-points}"), FACTION_POINTS(TagType.FACTION, "{faction-points}"),
/** /**
* General variables, require no faction or player * General variables, require no faction or player
*/ */
MAX_WARPS(TagType.GENERAL, "{max-warps}"), MAX_WARPS(TagType.GENERAL, "{max-warps}"),
MAX_ALLIES(TagType.GENERAL, "{max-allies}"), MAX_ALLIES(TagType.GENERAL, "{max-allies}"),
MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"), MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"),
MAX_TRUCES(TagType.GENERAL, "{max-truces}"), MAX_TRUCES(TagType.GENERAL, "{max-truces}"),
FACTIONLESS(TagType.GENERAL, "{factionless}"), FACTIONLESS(TagType.GENERAL, "{factionless}"),
TOTAL_ONLINE(TagType.GENERAL, "{total-online}"); TOTAL_ONLINE(TagType.GENERAL, "{total-online}");
private TagType type; private TagType type;
private String tag; private String tag;
TagReplacer(TagType type, String tag) { TagReplacer(TagType type, String tag) {
this.type = type; this.type = type;
this.tag = tag; this.tag = tag;
} }
/** /**
* Returns a list of all the variables we can use for this type<br> * Returns a list of all the variables we can use for this type<br>
* *
* @param type the type we want * @param type the type we want
* @return a list of all the variables with this type * @return a list of all the variables with this type
*/ */
protected static List<TagReplacer> getByType(TagType type) { protected static List<TagReplacer> getByType(TagType type) {
List<TagReplacer> tagReplacers = new ArrayList<>(); List<TagReplacer> tagReplacers = new ArrayList<>();
for (TagReplacer tagReplacer : TagReplacer.values()) { for (TagReplacer tagReplacer : TagReplacer.values()) {
if (type == TagType.FANCY) { if (type == TagType.FANCY) {
if (tagReplacer.type == TagType.FANCY) { if (tagReplacer.type == TagType.FANCY) {
tagReplacers.add(tagReplacer); tagReplacers.add(tagReplacer);
} }
} else if (tagReplacer.type.id >= type.id) { } else if (tagReplacer.type.id >= type.id) {
tagReplacers.add(tagReplacer); tagReplacers.add(tagReplacer);
} }
} }
return tagReplacers; return tagReplacers;
} }
/** /**
* Protected access to this generic server related variable * Protected access to this generic server related variable
* *
* @return value for this generic server related variable<br> * @return value for this generic server related variable<br>
*/ */
protected String getValue() { protected String getValue() {
switch (this) { switch (this) {
case TOTAL_ONLINE: case TOTAL_ONLINE:
return String.valueOf(Bukkit.getOnlinePlayers().size()); return String.valueOf(Bukkit.getOnlinePlayers().size());
case FACTIONLESS: case FACTIONLESS:
return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size()); return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size());
case MAX_ALLIES: case MAX_ALLIES:
if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { if (P.p.getConfig().getBoolean("max-relations.enabled", true)) {
return String.valueOf(P.p.getConfig().getInt("max-relations.ally", 10)); return String.valueOf(P.p.getConfig().getInt("max-relations.ally", 10));
} }
return TL.GENERIC_INFINITY.toString(); return TL.GENERIC_INFINITY.toString();
case MAX_ENEMIES: case MAX_ENEMIES:
if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { if (P.p.getConfig().getBoolean("max-relations.enabled", true)) {
return String.valueOf(P.p.getConfig().getInt("max-relations.enemy", 10)); return String.valueOf(P.p.getConfig().getInt("max-relations.enemy", 10));
} }
return TL.GENERIC_INFINITY.toString(); return TL.GENERIC_INFINITY.toString();
case MAX_TRUCES: case MAX_TRUCES:
if (P.p.getConfig().getBoolean("max-relations.enabled", true)) { if (P.p.getConfig().getBoolean("max-relations.enabled", true)) {
return String.valueOf(P.p.getConfig().getInt("max-relations.truce", 10)); return String.valueOf(P.p.getConfig().getInt("max-relations.truce", 10));
} }
return TL.GENERIC_INFINITY.toString(); return TL.GENERIC_INFINITY.toString();
case MAX_WARPS: case MAX_WARPS:
return String.valueOf(P.p.getConfig().getInt("max-warps", 5)); return String.valueOf(P.p.getConfig().getInt("max-warps", 5));
default: default:
} }
return null; return null;
} }
/** /**
* Gets the value for this (as in the instance this is called from) variable! * Gets the value for this (as in the instance this is called from) variable!
* *
* @param fac Target faction * @param fac Target faction
* @param fp Target player (can be null) * @param fp Target player (can be null)
* @return the value for this enum! * @return the value for this enum!
*/ */
protected String getValue(Faction fac, FPlayer fp) { protected String getValue(Faction fac, FPlayer fp) {
if (this.type == TagType.GENERAL) { if (this.type == TagType.GENERAL) {
return getValue(); return getValue();
} }
boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); boolean minimal = P.p.getConfig().getBoolean("minimal-show", false);
if (fp != null) { if (fp != null) {
switch (this) { switch (this) {
case HEADER: case HEADER:
return P.p.txt.titleize(fac.getTag(fp)); return P.p.txt.titleize(fac.getTag(fp));
case PLAYER_NAME: case PLAYER_NAME:
return fp.getName(); return fp.getName();
case FACTION: case FACTION:
return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString(); return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString();
case LAST_SEEN: case LAST_SEEN:
String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; 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); return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized);
case PLAYER_GROUP: case PLAYER_GROUP:
return P.p.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); return P.p.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId())));
case PLAYER_BALANCE: case PLAYER_BALANCE:
return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance");
case PLAYER_POWER: case PLAYER_POWER:
return String.valueOf(fp.getPowerRounded()); return String.valueOf(fp.getPowerRounded());
case PLAYER_MAXPOWER: case PLAYER_MAXPOWER:
return String.valueOf(fp.getPowerMaxRounded()); return String.valueOf(fp.getPowerMaxRounded());
case PLAYER_KILLS: case PLAYER_KILLS:
return String.valueOf(fp.getKills()); return String.valueOf(fp.getKills());
case PLAYER_DEATHS: case PLAYER_DEATHS:
return String.valueOf(fp.getDeaths()); return String.valueOf(fp.getDeaths());
default: default:
} }
} }
switch (this) { switch (this) {
case DESCRIPTION: case DESCRIPTION:
return fac.getDescription(); return fac.getDescription();
case FACTION: case FACTION:
return fac.getTag(); return fac.getTag();
case JOINING: case JOINING:
return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString());
case PEACEFUL: case PEACEFUL:
return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : "";
case PERMANENT: case PERMANENT:
return fac.isPermanent() ? "permanent" : "{notPermanent}"; return fac.isPermanent() ? "permanent" : "{notPermanent}";
case CHUNKS: case CHUNKS:
return String.valueOf(fac.getLandRounded()); return String.valueOf(fac.getLandRounded());
case POWER: case POWER:
return String.valueOf(fac.getPowerRounded()); return String.valueOf(fac.getPowerRounded());
case MAX_POWER: case MAX_POWER:
return String.valueOf(fac.getPowerMaxRounded()); return String.valueOf(fac.getPowerMaxRounded());
case POWER_BOOST: case POWER_BOOST:
double powerBoost = fac.getPowerBoost(); double powerBoost = fac.getPowerBoost();
return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")");
case LEADER: case LEADER:
FPlayer fAdmin = fac.getFPlayerAdmin(); FPlayer fAdmin = fac.getFPlayerAdmin();
return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length());
case WARPS: case WARPS:
return String.valueOf(fac.getWarps().size()); return String.valueOf(fac.getWarps().size());
case CREATE_DATE: case CREATE_DATE:
return TL.sdf.format(fac.getFoundedDate()); return TL.sdf.format(fac.getFoundedDate());
case RAIDABLE: case RAIDABLE:
boolean raid = P.p.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded(); boolean raid = P.p.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded();
return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString();
case HOME_WORLD: case HOME_WORLD:
return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}"; return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}";
case HOME_X: case HOME_X:
return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}"; return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}";
case HOME_Y: case HOME_Y:
return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}"; return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}";
case HOME_Z: case HOME_Z:
return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}"; return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}";
case LAND_VALUE: case LAND_VALUE:
return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value"); return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value");
case LAND_REFUND: case LAND_REFUND:
return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("refund"); return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("refund");
case BANK_BALANCE: case BANK_BALANCE:
if (Econ.shouldBeUsed()) { if (Econ.shouldBeUsed()) {
return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance"); return Conf.bankEnabled ? Econ.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance");
} }
return minimal ? null : TL.ECON_OFF.format("balance"); return minimal ? null : TL.ECON_OFF.format("balance");
case ALLIES_COUNT: case ALLIES_COUNT:
return String.valueOf(fac.getRelationCount(Relation.ALLY)); return String.valueOf(fac.getRelationCount(Relation.ALLY));
case ENEMIES_COUNT: case ENEMIES_COUNT:
return String.valueOf(fac.getRelationCount(Relation.ENEMY)); return String.valueOf(fac.getRelationCount(Relation.ENEMY));
case TRUCES_COUNT: case TRUCES_COUNT:
return String.valueOf(fac.getRelationCount(Relation.TRUCE)); return String.valueOf(fac.getRelationCount(Relation.TRUCE));
case ONLINE_COUNT: case ONLINE_COUNT:
if (fp != null && fp.isOnline()) { if (fp != null && fp.isOnline()) {
return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size());
} else { } else {
// Only console should ever get here. // Only console should ever get here.
return String.valueOf(fac.getFPlayersWhereOnline(true).size()); return String.valueOf(fac.getFPlayersWhereOnline(true).size());
} }
case OFFLINE_COUNT: case OFFLINE_COUNT:
return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size()); return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size());
case FACTION_SIZE: case FACTION_SIZE:
return String.valueOf(fac.getFPlayers().size()); return String.valueOf(fac.getFPlayers().size());
case FACTION_KILLS: case FACTION_KILLS:
return String.valueOf(fac.getKills()); return String.valueOf(fac.getKills());
case FACTION_DEATHS: case FACTION_DEATHS:
return String.valueOf(fac.getDeaths()); return String.valueOf(fac.getDeaths());
case FACTION_BANCOUNT: case FACTION_BANCOUNT:
return String.valueOf(fac.getBannedPlayers().size()); return String.valueOf(fac.getBannedPlayers().size());
case FACTION_STRIKES: case FACTION_STRIKES:
return String.valueOf(fac.getStrikes()); return String.valueOf(fac.getStrikes());
case FACTION_POINTS: case FACTION_POINTS:
return String.valueOf(fac.getPoints()); return String.valueOf(fac.getPoints());
default: default:
} }
return null; return null;
} }
/** /**
* @param original raw line with variables * @param original raw line with variables
* @param value what to replace var in raw line with * @param value what to replace var in raw line with
* @return the string with the new value * @return the string with the new value
*/ */
public String replace(String original, String value) { public String replace(String original, String value) {
return (original != null && value != null) ? original.replace(tag, value) : original; return (original != null && value != null) ? original.replace(tag, value) : original;
} }
/** /**
* @param toSearch raw line with variables * @param toSearch raw line with variables
* @return if the raw line contains this enums variable * @return if the raw line contains this enums variable
*/ */
public boolean contains(String toSearch) { public boolean contains(String toSearch) {
if (tag == null) { if (tag == null) {
return false; return false;
} }
return toSearch.contains(tag); return toSearch.contains(tag);
} }
/** /**
* Gets the tag associated with this enum that we should replace * Gets the tag associated with this enum that we should replace
* *
* @return the {....} variable that is located in config * @return the {....} variable that is located in config
*/ */
public String getTag() { public String getTag() {
return this.tag; return this.tag;
} }
protected enum TagType { protected enum TagType {
FANCY(0), PLAYER(1), FACTION(2), GENERAL(3); FANCY(0), PLAYER(1), FACTION(2), GENERAL(3);
public int id; public int id;
TagType(int id) { TagType(int id) {
this.id = id; this.id = id;
} }
} }
} }

View File

@ -19,275 +19,275 @@ import static com.massivecraft.factions.zcore.util.TagReplacer.TagType;
public class TagUtil { 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 * Replaces all variables in a plain raw line for a faction
* *
* @param faction for faction * @param faction for faction
* @param line raw line from config with variables to replace for * @param line raw line from config with variables to replace for
* @return clean line * @return clean line
*/ */
public static String parsePlain(Faction faction, String line) { public static String parsePlain(Faction faction, String line) {
for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) { for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) {
if (tagReplacer.contains(line)) { if (tagReplacer.contains(line)) {
line = tagReplacer.replace(line, tagReplacer.getValue(faction, null)); line = tagReplacer.replace(line, tagReplacer.getValue(faction, null));
} }
} }
return line; return line;
} }
/** /**
* Replaces all variables in a plain raw line for a player * Replaces all variables in a plain raw line for a player
* *
* @param fplayer for player * @param fplayer for player
* @param line raw line from config with variables to replace for * @param line raw line from config with variables to replace for
* @return clean line * @return clean line
*/ */
public static String parsePlain(FPlayer fplayer, String line) { public static String parsePlain(FPlayer fplayer, String line) {
for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) {
if (tagReplacer.contains(line)) { if (tagReplacer.contains(line)) {
String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer); String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer);
if (rep == null) { if (rep == null) {
rep = ""; // this should work, but it's not a good way to handle whatever is going wrong rep = ""; // this should work, but it's not a good way to handle whatever is going wrong
} }
line = tagReplacer.replace(line, rep); line = tagReplacer.replace(line, rep);
} }
} }
return line; return line;
} }
/** /**
* Replaces all variables in a plain raw line for a faction, using relations from fplayer * Replaces all variables in a plain raw line for a faction, using relations from fplayer
* *
* @param faction for faction * @param faction for faction
* @param fplayer from player * @param fplayer from player
* @param line raw line from config with variables to replace for * @param line raw line from config with variables to replace for
* @return clean line * @return clean line
*/ */
public static String parsePlain(Faction faction, FPlayer fplayer, String line) { public static String parsePlain(Faction faction, FPlayer fplayer, String line) {
for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) {
if (tagReplacer.contains(line)) { if (tagReplacer.contains(line)) {
String value = tagReplacer.getValue(faction, fplayer); String value = tagReplacer.getValue(faction, fplayer);
if (value != null) { if (value != null) {
line = tagReplacer.replace(line, value); line = tagReplacer.replace(line, value);
} else { } else {
return null; // minimal show, entire line to be ignored return null; // minimal show, entire line to be ignored
} }
} }
} }
return line; return line;
} }
/** /**
* Scan a line and parse the fancy variable into a fancy list * Scan a line and parse the fancy variable into a fancy list
* *
* @param faction for faction (viewers faction) * @param faction for faction (viewers faction)
* @param fme for player (viewer) * @param fme for player (viewer)
* @param line fancy message prefix * @param line fancy message prefix
* @return list of fancy msgs * @return list of fancy msgs
*/ */
public static List<FancyMessage> parseFancy(Faction faction, FPlayer fme, String line) { public static List<FancyMessage> parseFancy(Faction faction, FPlayer fme, String line) {
for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) {
if (tagReplacer.contains(line)) { if (tagReplacer.contains(line)) {
String clean = line.replace(tagReplacer.getTag(), ""); // remove tag String clean = line.replace(tagReplacer.getTag(), ""); // remove tag
return getFancy(faction, fme, tagReplacer, clean); return getFancy(faction, fme, tagReplacer, clean);
} }
} }
return null; return null;
} }
public static String parsePlaceholders(Player player, String line) { public static String parsePlaceholders(Player player, String line) {
if (P.p.isClipPlaceholderAPIHooked() && player.isOnline()) { if (P.p.isClipPlaceholderAPIHooked() && player.isOnline()) {
line = PlaceholderAPI.setPlaceholders(player, line); line = PlaceholderAPI.setPlaceholders(player, line);
} }
if (P.p.isMVdWPlaceholderAPIHooked() && player.isOnline()) { if (P.p.isMVdWPlaceholderAPIHooked() && player.isOnline()) {
line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line);
} }
return line; return line;
} }
/** /**
* Checks if a line has fancy variables * Checks if a line has fancy variables
* *
* @param line raw line from config with variables * @param line raw line from config with variables
* @return if the line has fancy variables * @return if the line has fancy variables
*/ */
public static boolean hasFancy(String line) { public static boolean hasFancy(String line) {
for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) {
if (tagReplacer.contains(line)) { if (tagReplacer.contains(line)) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Lets get fancy. * Lets get fancy.
* *
* @param target Faction to get relate from * @param target Faction to get relate from
* @param fme Player to relate to * @param fme Player to relate to
* @param prefix First part of the fancy message * @param prefix First part of the fancy message
* @return list of fancy messages to send * @return list of fancy messages to send
*/ */
protected static List<FancyMessage> getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) { protected static List<FancyMessage> getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) {
List<FancyMessage> fancyMessages = new ArrayList<>(); List<FancyMessage> fancyMessages = new ArrayList<>();
boolean minimal = P.p.getConfig().getBoolean("minimal-show", false); boolean minimal = P.p.getConfig().getBoolean("minimal-show", false);
switch (type) { switch (type) {
case ALLIES_LIST: case ALLIES_LIST:
FancyMessage currentAllies = P.p.txt.parseFancy(prefix); FancyMessage currentAllies = P.p.txt.parseFancy(prefix);
boolean firstAlly = true; boolean firstAlly = true;
for (Faction otherFaction : Factions.getInstance().getAllFactions()) { for (Faction otherFaction : Factions.getInstance().getAllFactions()) {
if (otherFaction == target) { if (otherFaction == target) {
continue; continue;
} }
String s = otherFaction.getTag(fme); String s = otherFaction.getTag(fme);
if (otherFaction.getRelationTo(target).isAlly()) { if (otherFaction.getRelationTo(target).isAlly()) {
currentAllies.then(firstAlly ? s : ", " + s); currentAllies.then(firstAlly ? s : ", " + s);
currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor());
firstAlly = false; firstAlly = false;
if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) { if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(currentAllies); fancyMessages.add(currentAllies);
currentAllies = new FancyMessage(""); currentAllies = new FancyMessage("");
} }
} }
} }
fancyMessages.add(currentAllies); fancyMessages.add(currentAllies);
return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch
case ENEMIES_LIST: case ENEMIES_LIST:
FancyMessage currentEnemies = P.p.txt.parseFancy(prefix); FancyMessage currentEnemies = P.p.txt.parseFancy(prefix);
boolean firstEnemy = true; boolean firstEnemy = true;
for (Faction otherFaction : Factions.getInstance().getAllFactions()) { for (Faction otherFaction : Factions.getInstance().getAllFactions()) {
if (otherFaction == target) { if (otherFaction == target) {
continue; continue;
} }
String s = otherFaction.getTag(fme); String s = otherFaction.getTag(fme);
if (otherFaction.getRelationTo(target).isEnemy()) { if (otherFaction.getRelationTo(target).isEnemy()) {
currentEnemies.then(firstEnemy ? s : ", " + s); currentEnemies.then(firstEnemy ? s : ", " + s);
currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor());
firstEnemy = false; firstEnemy = false;
if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) { if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(currentEnemies); fancyMessages.add(currentEnemies);
currentEnemies = new FancyMessage(""); currentEnemies = new FancyMessage("");
} }
} }
} }
fancyMessages.add(currentEnemies); fancyMessages.add(currentEnemies);
return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch
case TRUCES_LIST: case TRUCES_LIST:
FancyMessage currentTruces = P.p.txt.parseFancy(prefix); FancyMessage currentTruces = P.p.txt.parseFancy(prefix);
boolean firstTruce = true; boolean firstTruce = true;
for (Faction otherFaction : Factions.getInstance().getAllFactions()) { for (Faction otherFaction : Factions.getInstance().getAllFactions()) {
if (otherFaction == target) { if (otherFaction == target) {
continue; continue;
} }
String s = otherFaction.getTag(fme); String s = otherFaction.getTag(fme);
if (otherFaction.getRelationTo(target).isTruce()) { if (otherFaction.getRelationTo(target).isTruce()) {
currentTruces.then(firstTruce ? s : ", " + s); currentTruces.then(firstTruce ? s : ", " + s);
currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor());
firstTruce = false; firstTruce = false;
if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) { if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(currentTruces); fancyMessages.add(currentTruces);
currentTruces = new FancyMessage(""); currentTruces = new FancyMessage("");
} }
} }
} }
fancyMessages.add(currentTruces); fancyMessages.add(currentTruces);
return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch
case ONLINE_LIST: case ONLINE_LIST:
FancyMessage currentOnline = P.p.txt.parseFancy(prefix); FancyMessage currentOnline = P.p.txt.parseFancy(prefix);
boolean firstOnline = true; boolean firstOnline = true;
for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) {
if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) {
continue; // skip continue; // skip
} }
String name = p.getNameAndTitle(); String name = p.getNameAndTitle();
currentOnline.then(firstOnline ? name : ", " + name); currentOnline.then(firstOnline ? name : ", " + name);
currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor());
firstOnline = false; firstOnline = false;
if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(currentOnline); fancyMessages.add(currentOnline);
currentOnline = new FancyMessage(""); currentOnline = new FancyMessage("");
} }
} }
fancyMessages.add(currentOnline); fancyMessages.add(currentOnline);
return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch
case OFFLINE_LIST: case OFFLINE_LIST:
FancyMessage currentOffline = P.p.txt.parseFancy(prefix); FancyMessage currentOffline = P.p.txt.parseFancy(prefix);
boolean firstOffline = true; boolean firstOffline = true;
for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) { for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) {
String name = p.getNameAndTitle(); String name = p.getNameAndTitle();
// Also make sure to add players that are online BUT can't be seen. // 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()))) { if (!p.isOnline() || (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer()))) {
currentOffline.then(firstOffline ? name : ", " + name); currentOffline.then(firstOffline ? name : ", " + name);
currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor());
firstOffline = false; firstOffline = false;
if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(currentOffline); fancyMessages.add(currentOffline);
currentOffline = new FancyMessage(""); currentOffline = new FancyMessage("");
} }
} }
} }
fancyMessages.add(currentOffline); fancyMessages.add(currentOffline);
return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch
case ALTS: case ALTS:
FancyMessage alts = P.p.txt.parseFancy(prefix); FancyMessage alts = P.p.txt.parseFancy(prefix);
boolean firstAlt = true; boolean firstAlt = true;
for (FPlayer p : target.getAltPlayers()) { for (FPlayer p : target.getAltPlayers()) {
String name = p.getName(); String name = p.getName();
ChatColor color; ChatColor color;
if (p.isOnline()) { if (p.isOnline()) {
color = ChatColor.GREEN; color = ChatColor.GREEN;
} else { } else {
color = ChatColor.RED; color = ChatColor.RED;
} }
alts.then(firstAlt ? name : ", " + name); alts.then(firstAlt ? name : ", " + name);
alts.tooltip(tipPlayer(p)).color(color); alts.tooltip(tipPlayer(p)).color(color);
firstAlt = false; firstAlt = false;
if (alts.toJSONString().length() > ARBITRARY_LIMIT) { if (alts.toJSONString().length() > ARBITRARY_LIMIT) {
fancyMessages.add(alts); fancyMessages.add(alts);
currentOffline = new FancyMessage(""); currentOffline = new FancyMessage("");
} }
} }
fancyMessages.add(alts); fancyMessages.add(alts);
return firstAlt && minimal ? null : fancyMessages; return firstAlt && minimal ? null : fancyMessages;
default: default:
break; break;
} }
return null; return null;
} }
/** /**
* Parses tooltip variables from config <br> Supports variables for factions only (type 2) * Parses tooltip variables from config <br> Supports variables for factions only (type 2)
* *
* @param faction faction to tooltip for * @param faction faction to tooltip for
* @return list of tooltips for a fancy message * @return list of tooltips for a fancy message
*/ */
private static List<String> tipFaction(Faction faction) { private static List<String> tipFaction(Faction faction) {
List<String> lines = new ArrayList<>(); List<String> lines = new ArrayList<>();
for (String line : P.p.getConfig().getStringList("tooltips.list")) { for (String line : P.p.getConfig().getStringList("tooltips.list")) {
lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line)));
} }
return lines; return lines;
} }
/** /**
* Parses tooltip variables from config <br> Supports variables for players and factions (types 1 and 2) * Parses tooltip variables from config <br> Supports variables for players and factions (types 1 and 2)
* *
* @param fplayer player to tooltip for * @param fplayer player to tooltip for
* @return list of tooltips for a fancy message * @return list of tooltips for a fancy message
*/ */
private static List<String> tipPlayer(FPlayer fplayer) { private static List<String> tipPlayer(FPlayer fplayer) {
List<String> lines = new ArrayList<>(); List<String> lines = new ArrayList<>();
for (String line : P.p.getConfig().getStringList("tooltips.show")) { for (String line : P.p.getConfig().getStringList("tooltips.show")) {
lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line)));
} }
return lines; return lines;
} }
} }

View File

@ -10,223 +10,223 @@ import java.util.regex.Pattern;
public class TextUtil { public class TextUtil {
public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>");
private final static String titleizeLine = repeat("-", 52); private final static String titleizeLine = repeat("-", 52);
// -------------------------------------------- // // -------------------------------------------- //
// Top-level parsing functions. // Top-level parsing functions.
// -------------------------------------------- // // -------------------------------------------- //
private final static int titleizeBalance = -1; private final static int titleizeBalance = -1;
public Map<String, String> tags; public Map<String, String> tags;
// -------------------------------------------- // // -------------------------------------------- //
// Tag parsing // Tag parsing
// -------------------------------------------- // // -------------------------------------------- //
public TextUtil() { public TextUtil() {
this.tags = new HashMap<>(); this.tags = new HashMap<>();
} }
public static String replaceTags(String str, Map<String, String> tags) { public static String replaceTags(String str, Map<String, String> tags) {
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
Matcher matcher = patternTag.matcher(str); Matcher matcher = patternTag.matcher(str);
while (matcher.find()) { while (matcher.find()) {
String tag = matcher.group(1); String tag = matcher.group(1);
String repl = tags.get(tag); String repl = tags.get(tag);
if (repl == null) { if (repl == null) {
matcher.appendReplacement(ret, "<" + tag + ">"); matcher.appendReplacement(ret, "<" + tag + ">");
} else { } else {
matcher.appendReplacement(ret, repl); matcher.appendReplacement(ret, repl);
} }
} }
matcher.appendTail(ret); matcher.appendTail(ret);
return ret.toString(); return ret.toString();
} }
public static FancyMessage toFancy(String first) { public static FancyMessage toFancy(String first) {
String text = ""; String text = "";
FancyMessage message = new FancyMessage(text); FancyMessage message = new FancyMessage(text);
ChatColor color = null; ChatColor color = null;
char[] chars = first.toCharArray(); char[] chars = first.toCharArray();
for (int i = 0; i < chars.length; i++) { for (int i = 0; i < chars.length; i++) {
// changed this so javadocs wont throw an error // changed this so javadocs wont throw an error
String compareChar = chars[i] + ""; String compareChar = chars[i] + "";
if (compareChar.equals("§")) { if (compareChar.equals("§")) {
if (color != null) { if (color != null) {
if (color.isColor()) { if (color.isColor()) {
message.then(text).color(color); message.then(text).color(color);
} else { } else {
message.then(text).style(color); message.then(text).style(color);
} }
text = ""; text = "";
color = ChatColor.getByChar(chars[i + 1]); color = ChatColor.getByChar(chars[i + 1]);
} else { } else {
color = ChatColor.getByChar(chars[i + 1]); color = ChatColor.getByChar(chars[i + 1]);
} }
i++; // skip color char i++; // skip color char
} else { } else {
text += chars[i]; text += chars[i];
} }
} }
if (text.length() > 0) { if (text.length() > 0) {
if (color != null) { if (color != null) {
if (color.isColor()) { if (color.isColor()) {
message.then(text).color(color); message.then(text).color(color);
} else { } else {
message.then(text).style(color); message.then(text).style(color);
} }
} else { } else {
message.text(text); message.text(text);
} }
} }
return message; return message;
} }
// -------------------------------------------- // // -------------------------------------------- //
// Fancy parsing // Fancy parsing
// -------------------------------------------- // // -------------------------------------------- //
public static String parseColor(String string) { public static String parseColor(String string) {
string = parseColorAmp(string); string = parseColorAmp(string);
string = parseColorAcc(string); string = parseColorAcc(string);
string = parseColorTags(string); string = parseColorTags(string);
return ChatColor.translateAlternateColorCodes('&', string); return ChatColor.translateAlternateColorCodes('&', string);
} }
public static String parseColorAmp(String 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.replaceAll("(&([a-z0-9]))", "\u00A7$2"); string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2");
string = string.replace("&&", "&"); string = string.replace("&&", "&");
return string; return string;
} }
// -------------------------------------------- // // -------------------------------------------- //
// Color parsing // Color parsing
// -------------------------------------------- // // -------------------------------------------- //
public static String parseColorAcc(String string) { 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()); 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) { public static String parseColorTags(String string) {
return string.replace("<empty>", "").replace("<black>", "\u00A70").replace("<navy>", "\u00A71").replace("<green>", "\u00A72").replace("<teal>", "\u00A73").replace("<red>", "\u00A74").replace("<purple>", "\u00A75").replace("<gold>", "\u00A76").replace("<silver>", "\u00A77").replace("<gray>", "\u00A78").replace("<blue>", "\u00A79").replace("<lime>", "\u00A7a").replace("<aqua>", "\u00A7b").replace("<rose>", "\u00A7c").replace("<pink>", "\u00A7d").replace("<yellow>", "\u00A7e").replace("<white>", "\u00A7f"); return string.replace("<empty>", "").replace("<black>", "\u00A70").replace("<navy>", "\u00A71").replace("<green>", "\u00A72").replace("<teal>", "\u00A73").replace("<red>", "\u00A74").replace("<purple>", "\u00A75").replace("<gold>", "\u00A76").replace("<silver>", "\u00A77").replace("<gray>", "\u00A78").replace("<blue>", "\u00A79").replace("<lime>", "\u00A7a").replace("<aqua>", "\u00A7b").replace("<rose>", "\u00A7c").replace("<pink>", "\u00A7d").replace("<yellow>", "\u00A7e").replace("<white>", "\u00A7f");
} }
public static String upperCaseFirst(String string) { public static String upperCaseFirst(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1); return string.substring(0, 1).toUpperCase() + string.substring(1);
} }
public static String implode(List<String> list, String glue) { public static String implode(List<String> list, String glue) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for (int i = 0; i < list.size(); i++) for (int i = 0; i < list.size(); i++)
ret.append(glue).append(list.get(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) { public static String repeat(String s, int times) {
return times > 0 ? s + repeat(s, times - 1) : ""; return times > 0 ? s + repeat(s, times - 1) : "";
} }
public static String getMaterialName(Material material) { public static String getMaterialName(Material material) {
return material.toString().replace('_', ' ').toLowerCase(); return material.toString().replace('_', ' ').toLowerCase();
} }
// -------------------------------------------- // // -------------------------------------------- //
// Material name tools // Material name tools
// -------------------------------------------- // // -------------------------------------------- //
public static String getBestStartWithCI(Collection<String> candidates, String start) { public static String getBestStartWithCI(Collection<String> candidates, String start) {
String ret = null; String ret = null;
int best = 0; int best = 0;
start = start.toLowerCase(); start = start.toLowerCase();
int minlength = start.length(); int minlength = start.length();
for (String candidate : candidates) { for (String candidate : candidates) {
if (candidate.length() < minlength) { if (candidate.length() < minlength) {
continue; continue;
} }
if (!candidate.toLowerCase().startsWith(start)) { if (!candidate.toLowerCase().startsWith(start)) {
continue; continue;
} }
// The closer to zero the better // The closer to zero the better
int lendiff = candidate.length() - minlength; int lendiff = candidate.length() - minlength;
if (lendiff == 0) { if (lendiff == 0) {
return candidate; return candidate;
} }
if (lendiff < best || best == 0) { if (lendiff < best || best == 0) {
best = lendiff; best = lendiff;
ret = candidate; ret = candidate;
} }
} }
return ret; return ret;
} }
public String parse(String str, Object... args) { public String parse(String str, Object... args) {
return String.format(this.parse(str), 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) { public String parse(String str) {
return this.parseTags(parseColor(str)); return this.parseTags(parseColor(str));
} }
public String parseTags(String str) { public String parseTags(String str) {
return replaceTags(str, this.tags); return replaceTags(str, this.tags);
} }
public FancyMessage parseFancy(String prefix) { public FancyMessage parseFancy(String prefix) {
return toFancy(parse(prefix)); return toFancy(parse(prefix));
} }
public String titleize(String str) { public String titleize(String str) {
String center = ChatColor.DARK_GRAY + "< " + parseTags("<l>") + str + parseTags("<a>") + ChatColor.DARK_GRAY + " >"; String center = ChatColor.DARK_GRAY + "< " + parseTags("<l>") + str + parseTags("<a>") + ChatColor.DARK_GRAY + " >";
int centerlen = ChatColor.stripColor(center).length(); int centerlen = ChatColor.stripColor(center).length();
int pivot = titleizeLine.length() / 2; int pivot = titleizeLine.length() / 2;
int eatLeft = (centerlen / 2) - titleizeBalance; int eatLeft = (centerlen / 2) - titleizeBalance;
int eatRight = (centerlen - eatLeft) + titleizeBalance; int eatRight = (centerlen - eatLeft) + titleizeBalance;
if (eatLeft < pivot) { if (eatLeft < pivot) {
return parseTags("<a>") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight); return parseTags("<a>") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight);
} else { } else {
return parseTags("<a>") + center; return parseTags("<a>") + center;
} }
} }
public ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title) { public ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title) {
ArrayList<String> ret = new ArrayList<>(); ArrayList<String> ret = new ArrayList<>();
int pageZeroBased = pageHumanBased - 1; int pageZeroBased = pageHumanBased - 1;
int pageheight = 9; int pageheight = 9;
int pagecount = (lines.size() / pageheight) + 1; int pagecount = (lines.size() / pageheight) + 1;
ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount));
if (pagecount == 0) { if (pagecount == 0) {
ret.add(this.parseTags(TL.NOPAGES.toString())); ret.add(this.parseTags(TL.NOPAGES.toString()));
return ret; return ret;
} else if (pageZeroBased < 0 || pageHumanBased > pagecount) { } else if (pageZeroBased < 0 || pageHumanBased > pagecount) {
ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount)));
return ret; return ret;
} }
int from = pageZeroBased * pageheight; int from = pageZeroBased * pageheight;
int to = from + pageheight; int to = from + pageheight;
if (to > lines.size()) { if (to > lines.size()) {
to = lines.size(); to = lines.size();
} }
ret.addAll(lines.subList(from, to)); ret.addAll(lines.subList(from, to));
return ret; return ret;
} }
} }

View File

@ -18,83 +18,83 @@ import java.util.concurrent.Callable;
*/ */
public class UUIDFetcher implements Callable<Map<String, UUID>> { public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100; private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser(); private final JSONParser jsonParser = new JSONParser();
private final List<String> names; private final List<String> names;
private final boolean rateLimiting; private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) { public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names); this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting; this.rateLimiting = rateLimiting;
} }
public UUIDFetcher(List<String> names) { public UUIDFetcher(List<String> names) {
this(names, true); this(names, true);
} }
private static void writeBody(HttpURLConnection connection, String body) throws Exception { private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream(); OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes()); stream.write(body.getBytes());
stream.flush(); stream.flush();
stream.close(); stream.close();
} }
private static HttpURLConnection createConnection() throws Exception { private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL); URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
return connection; return connection;
} }
private static UUID getUUID(String id) { 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)); 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) { public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits()); byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits()); byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array(); return byteBuffer.array();
} }
public static UUID fromBytes(byte[] array) { public static UUID fromBytes(byte[] array) {
if (array.length != 16) { if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length); throw new IllegalArgumentException("Illegal byte array length: " + array.length);
} }
ByteBuffer byteBuffer = ByteBuffer.wrap(array); ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong(); long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong(); long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant); return new UUID(mostSignificant, leastSignificant);
} }
public static UUID getUUIDOf(String name) throws Exception { public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Collections.singletonList(name)).call().get(name); return new UUIDFetcher(Collections.singletonList(name)).call().get(name);
} }
public Map<String, UUID> call() throws Exception { public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<>(); Map<String, UUID> uuidMap = new HashMap<>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) { for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection(); HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body); writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) { for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile; JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name"); String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id); UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
if (rateLimiting && i != requests - 1) { if (rateLimiting && i != requests - 1) {
Thread.sleep(100L); Thread.sleep(100L);
} }
} }
return uuidMap; return uuidMap;
} }
} }