Search in sources :

Example 1 with Jail

use of com.palmergames.bukkit.towny.object.jail.Jail in project Towny by TownyAdvanced.

the class JailUtil method unJailResident.

/**
 * Unjails a resident.
 *
 * @param resident Resident being unjailed.
 * @param reason UnJailReason the resident is unjailed for.
 */
public static void unJailResident(Resident resident, UnJailReason reason) {
    Jail jail = resident.getJail();
    String jailName = jail.hasName() ? jail.getName() : ", cell unknown.";
    Town town = null;
    switch(reason) {
        case ESCAPE:
            town = resident.getTownOrNull();
            // First show a message to the resident, either by broadcasting to the resident's town or just the resident (if they have no town.)
            if (town != null)
                TownyMessaging.sendPrefixedTownMessage(town, Translatable.of("msg_player_escaped_jail_into_wilderness", resident.getName(), jail.getWildName()));
            else
                TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_been_freed_from_jail"));
            // Second, show a message to the town which has just had a prisoner escape.
            if (town != null && !town.getUUID().equals(jail.getTown().getUUID()))
                TownyMessaging.sendPrefixedTownMessage(jail.getTown(), Translatable.of("msg_player_escaped_jail_into_wilderness", resident.getName(), jail.getWildName()));
            break;
        case BAIL:
            teleportAwayFromJail(resident);
            TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_paid_bail"));
            TownyMessaging.sendPrefixedTownMessage(jail.getTown(), Translatable.of("msg_has_paid_bail", resident.getName()));
            break;
        case SENTENCE_SERVED:
            teleportAwayFromJail(resident);
            TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_served_your_sentence_and_are_free"));
            TownyMessaging.sendPrefixedTownMessage(jail.getTown(), Translatable.of("msg_x_has_served_their_sentence_and_is_free", resident.getName()));
            break;
        case LEFT_TOWN:
            town = resident.getTownOrNull();
            TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_been_freed_from_jail"));
            TownyMessaging.sendPrefixedTownMessage(town, Translatable.of("msg_player_escaped_jail_by_leaving_town", resident.getName()));
            break;
        case PARDONED:
        case JAIL_DELETED:
        case ADMIN:
            teleportAwayFromJail(resident);
            TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_been_freed_from_jail"));
            TownyMessaging.sendPrefixedTownMessage(jail.getTown(), Translatable.of("msg_x_has_been_freed_from_x", resident.getName(), jailName));
            break;
        case JAILBREAK:
            TownyMessaging.sendMsg(resident, Translatable.of("msg_you_have_been_freed_via_jailbreak"));
            break;
        default:
    }
    TownyUniverse.getInstance().getJailedResidentMap().remove(resident);
    resident.setJailCell(0);
    resident.setJailHours(0);
    resident.setJail(null);
    resident.save();
    Bukkit.getPluginManager().callEvent(new ResidentUnjailEvent(resident));
}
Also used : Town(com.palmergames.bukkit.towny.object.Town) Jail(com.palmergames.bukkit.towny.object.jail.Jail) ResidentUnjailEvent(com.palmergames.bukkit.towny.event.resident.ResidentUnjailEvent)

Example 2 with Jail

use of com.palmergames.bukkit.towny.object.jail.Jail in project Towny by TownyAdvanced.

the class TownySQLSource method loadTown.

private boolean loadTown(ResultSet rs) {
    String line;
    String[] tokens;
    String search;
    String name = null;
    try {
        Town town = universe.getTown(rs.getString("name"));
        if (town == null) {
            TownyMessaging.sendErrorMsg("SQL: Load Town " + rs.getString("name") + ". Town was not registered properly on load!");
            return false;
        }
        name = town.getName();
        TownyMessaging.sendDebugMsg("Loading town " + name);
        try {
            Resident res = universe.getResident(rs.getString("mayor"));
            if (res == null)
                throw new TownyException();
            town.forceSetMayor(res);
        } catch (TownyException e1) {
            e1.getMessage();
            if (town.getResidents().size() == 0) {
                deleteTown(town);
                return true;
            } else {
                town.findNewMayor();
            }
        }
        town.setBoard(rs.getString("townBoard"));
        line = rs.getString("tag");
        if (line != null)
            town.setTag(line);
        town.setPermissions(rs.getString("protectionStatus").replaceAll("#", ","));
        town.setBonusBlocks(rs.getInt("bonus"));
        town.setTaxPercentage(rs.getBoolean("taxpercent"));
        town.setTaxes(rs.getFloat("taxes"));
        town.setMaxPercentTaxAmount(rs.getFloat("maxPercentTaxAmount"));
        town.setHasUpkeep(rs.getBoolean("hasUpkeep"));
        town.setHasUnlimitedClaims(rs.getBoolean("hasUnlimitedClaims"));
        town.setPlotPrice(rs.getFloat("plotPrice"));
        town.setPlotTax(rs.getFloat("plotTax"));
        town.setEmbassyPlotPrice(rs.getFloat("embassyPlotPrice"));
        town.setEmbassyPlotTax(rs.getFloat("embassyPlotTax"));
        town.setCommercialPlotPrice(rs.getFloat("commercialPlotPrice"));
        town.setCommercialPlotTax(rs.getFloat("commercialPlotTax"));
        town.setSpawnCost(rs.getFloat("spawnCost"));
        town.setOpen(rs.getBoolean("open"));
        town.setPublic(rs.getBoolean("public"));
        town.setConquered(rs.getBoolean("conquered"));
        town.setAdminDisabledPVP(rs.getBoolean("admindisabledpvp"));
        town.setAdminEnabledPVP(rs.getBoolean("adminenabledpvp"));
        town.setJoinedNationAt(rs.getLong("joinedNationAt"));
        town.setMovedHomeBlockAt(rs.getLong("movedHomeBlockAt"));
        town.setPurchasedBlocks(rs.getInt("purchased"));
        town.setNationZoneOverride(rs.getInt("nationZoneOverride"));
        town.setNationZoneEnabled(rs.getBoolean("nationZoneEnabled"));
        line = rs.getString("maxPercentTaxAmount");
        if (line != null)
            town.setMaxPercentTaxAmount(Double.parseDouble(line));
        else
            town.setMaxPercentTaxAmount(TownySettings.getMaxTownTaxPercentAmount());
        line = rs.getString("homeBlock");
        if (line != null) {
            search = (line.contains("#")) ? "#" : ",";
            tokens = line.split(search);
            if (tokens.length == 3) {
                TownyWorld world = universe.getWorld(tokens[0]);
                if (world == null)
                    TownyMessaging.sendErrorMsg("[Warning] " + town.getName() + " homeBlock tried to load invalid world.");
                else {
                    try {
                        int x = Integer.parseInt(tokens[1]);
                        int z = Integer.parseInt(tokens[2]);
                        TownBlock homeBlock = universe.getTownBlock(new WorldCoord(world.getName(), x, z));
                        town.forceSetHomeBlock(homeBlock);
                    } catch (NumberFormatException e) {
                        TownyMessaging.sendErrorMsg("[Warning] " + town.getName() + " homeBlock tried to load invalid location.");
                    } catch (NotRegisteredException e) {
                        TownyMessaging.sendErrorMsg("[Warning] " + town.getName() + " homeBlock tried to load invalid TownBlock.");
                    } catch (TownyException e) {
                        TownyMessaging.sendErrorMsg("[Warning] " + town.getName() + " does not have a home block.");
                    }
                }
            }
        }
        line = rs.getString("spawn");
        if (line != null) {
            search = (line.contains("#")) ? "#" : ",";
            tokens = line.split(search);
            if (tokens.length >= 4)
                try {
                    World world = plugin.getServerWorld(tokens[0]);
                    double x = Double.parseDouble(tokens[1]);
                    double y = Double.parseDouble(tokens[2]);
                    double z = Double.parseDouble(tokens[3]);
                    Location loc = new Location(world, x, y, z);
                    if (tokens.length == 6) {
                        loc.setPitch(Float.parseFloat(tokens[4]));
                        loc.setYaw(Float.parseFloat(tokens[5]));
                    }
                    town.setSpawn(loc);
                } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                }
        }
        // Load outpost spawns
        line = rs.getString("outpostSpawns");
        if (line != null) {
            String[] outposts = line.split(";");
            for (String spawn : outposts) {
                search = (line.contains("#")) ? "#" : ",";
                tokens = spawn.split(search);
                if (tokens.length >= 4)
                    try {
                        World world = plugin.getServerWorld(tokens[0]);
                        double x = Double.parseDouble(tokens[1]);
                        double y = Double.parseDouble(tokens[2]);
                        double z = Double.parseDouble(tokens[3]);
                        Location loc = new Location(world, x, y, z);
                        if (tokens.length == 6) {
                            loc.setPitch(Float.parseFloat(tokens[4]));
                            loc.setYaw(Float.parseFloat(tokens[5]));
                        }
                        town.forceAddOutpostSpawn(loc);
                    } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                    }
            }
        }
        // Load legacy jail spawns into new Jail objects.
        line = rs.getString("jailSpawns");
        if (line != null) {
            String[] jails = line.split(";");
            for (String spawn : jails) {
                search = (line.contains("#")) ? "#" : ",";
                tokens = spawn.split(search);
                if (tokens.length >= 4)
                    try {
                        World world = plugin.getServerWorld(tokens[0]);
                        double x = Double.parseDouble(tokens[1]);
                        double y = Double.parseDouble(tokens[2]);
                        double z = Double.parseDouble(tokens[3]);
                        Location loc = new Location(world, x, y, z);
                        if (tokens.length == 6) {
                            loc.setPitch(Float.parseFloat(tokens[4]));
                            loc.setYaw(Float.parseFloat(tokens[5]));
                        }
                        TownBlock tb = universe.getTownBlock(WorldCoord.parseWorldCoord(loc));
                        if (tb == null)
                            continue;
                        Jail jail = new Jail(UUID.randomUUID(), town, tb, new ArrayList<>(Collections.singleton(loc)));
                        universe.registerJail(jail);
                        town.addJail(jail);
                        tb.setJail(jail);
                        jail.save();
                    } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                    }
            }
        }
        line = rs.getString("outlaws");
        if (line != null) {
            search = (line.contains("#")) ? "#" : ",";
            tokens = line.split(search);
            for (String token : tokens) {
                if (!token.isEmpty()) {
                    Resident resident = universe.getResident(token);
                    if (resident != null)
                        town.addOutlaw(resident);
                    else {
                        plugin.getLogger().warning(String.format("Loading Error: Cannot load outlaw with name '%s' for town '%s'! Skipping adding outlaw to town...", token, town.getName()));
                    }
                }
            }
        }
        try {
            town.setUUID(UUID.fromString(rs.getString("uuid")));
        } catch (IllegalArgumentException | NullPointerException ee) {
            town.setUUID(UUID.randomUUID());
        }
        universe.registerTownUUID(town);
        int conqueredDays = rs.getInt("conqueredDays");
        town.setConqueredDays(conqueredDays);
        try {
            long registered = rs.getLong("registered");
            town.setRegistered(registered);
        } catch (Exception ignored) {
            town.setRegistered(0);
        }
        try {
            line = rs.getString("metadata");
            if (line != null && !line.isEmpty()) {
                MetadataLoader.getInstance().deserializeMetadata(town, line);
            }
        } catch (SQLException ignored) {
        }
        try {
            line = rs.getString("nation");
            if (line != null && !line.isEmpty()) {
                Nation nation = universe.getNation(line);
                // Only set nation if it exists
                if (nation != null)
                    town.setNation(nation, false);
            }
        } catch (SQLException ignored) {
        }
        town.setRuined(rs.getBoolean("ruined"));
        town.setRuinedTime(rs.getLong("ruinedTime"));
        town.setNeutral(rs.getBoolean("neutral"));
        town.setDebtBalance(rs.getFloat("debtBalance"));
        line = rs.getString("primaryJail");
        if (line != null && !line.isEmpty()) {
            UUID uuid = UUID.fromString(line);
            if (universe.hasJail(uuid))
                town.setPrimaryJail(universe.getJail(uuid));
        }
        line = rs.getString("trustedResidents");
        if (line != null && !line.isEmpty()) {
            search = (line.contains("#")) ? "#" : ",";
            for (Resident resident : TownyAPI.getInstance().getResidents(toUUIDArray(line.split(search)))) town.addTrustedResident(resident);
        }
        line = rs.getString("mapColorHexCode");
        if (line != null)
            town.setMapColorHexCode(line);
        else
            town.setMapColorHexCode(MapUtil.generateRandomTownColourAsHexCode());
        line = rs.getString("allies");
        if (line != null && !line.isEmpty()) {
            search = (line.contains("#")) ? "#" : ",";
            List<UUID> uuids = Arrays.stream(line.split(search)).map(uuid -> UUID.fromString(uuid)).collect(Collectors.toList());
            town.loadAllies(TownyAPI.getInstance().getTowns(uuids));
        }
        line = rs.getString("enemies");
        if (line != null && !line.isEmpty()) {
            search = (line.contains("#")) ? "#" : ",";
            List<UUID> uuids = Arrays.stream(line.split(search)).map(uuid -> UUID.fromString(uuid)).collect(Collectors.toList());
            town.loadEnemies(TownyAPI.getInstance().getTowns(uuids));
        }
        return true;
    } catch (SQLException e) {
        TownyMessaging.sendErrorMsg("SQL: Load Town " + name + " sql Error - " + e.getMessage());
    } catch (Exception e) {
        TownyMessaging.sendErrorMsg("SQL: Load Town " + name + " unknown Error - ");
        e.printStackTrace();
    }
    return false;
}
Also used : Nation(com.palmergames.bukkit.towny.object.Nation) Arrays(java.util.Arrays) Connection(java.sql.Connection) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) Resident(com.palmergames.bukkit.towny.object.Resident) EmptyNationException(com.palmergames.bukkit.towny.exceptions.EmptyNationException) TownBlockTypeHandler(com.palmergames.bukkit.towny.object.TownBlockTypeHandler) Location(org.bukkit.Location) Gson(com.google.gson.Gson) World(org.bukkit.World) ResultSet(java.sql.ResultSet) Map(java.util.Map) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) Set(java.util.Set) BukkitTools(com.palmergames.bukkit.util.BukkitTools) UUID(java.util.UUID) MapUtil(com.palmergames.bukkit.towny.utils.MapUtil) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) List(java.util.List) HikariDataSource(com.zaxxer.hikari.HikariDataSource) BukkitTask(org.bukkit.scheduler.BukkitTask) Optional(java.util.Optional) Queue(java.util.Queue) Towny(com.palmergames.bukkit.towny.Towny) TownyMessaging(com.palmergames.bukkit.towny.TownyMessaging) FileMgmt(com.palmergames.util.FileMgmt) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TownyUniverse(com.palmergames.bukkit.towny.TownyUniverse) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) PlotGroup(com.palmergames.bukkit.towny.object.PlotGroup) PermissionData(com.palmergames.bukkit.towny.object.PermissionData) Town(com.palmergames.bukkit.towny.object.Town) StringMgmt(com.palmergames.util.StringMgmt) Nation(com.palmergames.bukkit.towny.object.Nation) Iterator(java.util.Iterator) TownyAPI(com.palmergames.bukkit.towny.TownyAPI) MetadataLoader(com.palmergames.bukkit.towny.object.metadata.MetadataLoader) File(java.io.File) HikariConfig(com.zaxxer.hikari.HikariConfig) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) Driver(java.sql.Driver) Statement(java.sql.Statement) TownySettings(com.palmergames.bukkit.towny.TownySettings) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) Collections(java.util.Collections) DriverManager(java.sql.DriverManager) Jail(com.palmergames.bukkit.towny.object.jail.Jail) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) World(org.bukkit.World) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) Town(com.palmergames.bukkit.towny.object.Town) Resident(com.palmergames.bukkit.towny.object.Resident) Jail(com.palmergames.bukkit.towny.object.jail.Jail) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) UUID(java.util.UUID) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) EmptyNationException(com.palmergames.bukkit.towny.exceptions.EmptyNationException) SQLException(java.sql.SQLException) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) Location(org.bukkit.Location)

Example 3 with Jail

use of com.palmergames.bukkit.towny.object.jail.Jail in project Towny by TownyAdvanced.

the class JailUtil method createJailPlot.

public static void createJailPlot(TownBlock townBlock, Town town, Location location) throws TownyException {
    UUID uuid = UUID.randomUUID();
    List<Location> jailSpawns = new ArrayList<Location>(1);
    jailSpawns.add(location);
    Jail jail = new Jail(uuid, town, townBlock, jailSpawns);
    TownyUniverse.getInstance().registerJail(jail);
    jail.save();
    town.addJail(jail);
    townBlock.setJail(jail);
}
Also used : ArrayList(java.util.ArrayList) Jail(com.palmergames.bukkit.towny.object.jail.Jail) UUID(java.util.UUID) Location(org.bukkit.Location)

Example 4 with Jail

use of com.palmergames.bukkit.towny.object.jail.Jail in project Towny by TownyAdvanced.

the class PlotCommand method parsePlotJailCell.

private void parsePlotJailCell(Player player, TownBlock townBlock, String[] args) {
    if (args.length == 0 || args[0].equalsIgnoreCase("?") || args[0].equalsIgnoreCase("help"))
        HelpMenu.PLOT_JAILCELL.send(player);
    try {
        if (!TownyUniverse.getInstance().getPermissionSource().has(player, PermissionNodes.TOWNY_COMMAND_PLOT_JAILCELL.getNode()))
            throw new TownyException("msg_err_command_disable");
        // Fail if the resident isn't registered. (Very unlikely.)
        Resident resident = TownyAPI.getInstance().getResident(player.getUniqueId());
        if (resident == null)
            return;
        // Fail if we're not in a jail plot.
        if (townBlock == null || !townBlock.isJail())
            throw new TownyException("msg_err_location_is_not_within_a_jail_plot");
        // Test we are allowed to work on this plot, and able to set a jail spawn.
        // If this fails it will trigger a TownyException.
        plotTestOwner(resident, townBlock);
        Jail jail = townBlock.getJail();
        if (args.length > 0) {
            if (args[0].equalsIgnoreCase("add")) {
                jail.addJailCell(player.getLocation());
                TownyMessaging.sendMsg(player, Translatable.of("msg_jail_cell_set"));
                jail.save();
            } else if (args[0].equalsIgnoreCase("remove")) {
                if (!jail.hasCells())
                    throw new TownyException(Translatable.of("msg_err_this_jail_has_no_cells"));
                if (jail.getCellMap().size() == 1)
                    throw new TownyException(Translatable.of("msg_err_you_cannot_remove_the_last_cell"));
                SpawnPointLocation cellLoc = SpawnPointLocation.parseSpawnPointLocation(player.getLocation());
                if (!jail.hasJailCell(cellLoc))
                    throw new TownyException(Translatable.of("msg_err_no_cell_found_at_this_location"));
                jail.removeJailCell(player.getLocation());
                TownyMessaging.sendMsg(player, Translatable.of("msg_jail_cell_removed"));
                jail.save();
            } else {
                HelpMenu.PLOT_JAILCELL.send(player);
            }
        }
    } catch (TownyException e) {
        TownyMessaging.sendErrorMsg(player, e.getMessage(player));
    }
}
Also used : SpawnPointLocation(com.palmergames.bukkit.towny.object.SpawnPointLocation) Resident(com.palmergames.bukkit.towny.object.Resident) Jail(com.palmergames.bukkit.towny.object.jail.Jail) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException)

Example 5 with Jail

use of com.palmergames.bukkit.towny.object.jail.Jail in project Towny by TownyAdvanced.

the class TownyFlatFileSource method loadTown.

@Override
public boolean loadTown(Town town) {
    String line = null;
    String[] tokens;
    String path = getTownFilename(town);
    File fileTown = new File(path);
    if (fileTown.exists() && fileTown.isFile()) {
        TownyMessaging.sendDebugMsg(Translation.of("flatfile_dbg_loading_town", town.getName()));
        try {
            HashMap<String, String> keys = FileMgmt.loadFileIntoHashMap(fileTown);
            line = keys.get("mayor");
            if (line != null)
                try {
                    Resident res = universe.getResident(line);
                    if (res == null)
                        throw new TownyException();
                    town.forceSetMayor(res);
                } catch (TownyException e1) {
                    if (town.getResidents().isEmpty())
                        deleteTown(town);
                    else
                        town.findNewMayor();
                    return true;
                }
            line = keys.get("outlaws");
            if (line != null) {
                tokens = line.split(",");
                for (String token : tokens) {
                    if (!token.isEmpty()) {
                        TownyMessaging.sendDebugMsg(Translation.of("flatfile_dbg_town_fetch_outlaw", token));
                        Resident outlaw = universe.getResident(token);
                        if (outlaw != null) {
                            try {
                                town.addOutlaw(outlaw);
                            } catch (AlreadyRegisteredException ex) {
                                TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_reading_outlaw_of_town_duplicate", town.getName(), token));
                            }
                        } else {
                            TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_reading_outlaw_of_town_not_exist", town.getName(), token));
                        }
                    }
                }
            }
            line = keys.get("townBoard");
            if (line != null)
                town.setBoard(line);
            line = keys.get("tag");
            if (line != null)
                town.setTag(line);
            line = keys.get("protectionStatus");
            if (line != null)
                town.setPermissions(line);
            line = keys.get("bonusBlocks");
            if (line != null)
                try {
                    town.setBonusBlocks(Integer.parseInt(line));
                } catch (Exception e) {
                    town.setBonusBlocks(0);
                }
            line = keys.get("purchasedBlocks");
            if (line != null)
                try {
                    town.setPurchasedBlocks(Integer.parseInt(line));
                } catch (Exception e) {
                    town.setPurchasedBlocks(0);
                }
            line = keys.get("plotPrice");
            if (line != null)
                try {
                    town.setPlotPrice(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setPlotPrice(0);
                }
            line = keys.get("hasUpkeep");
            if (line != null)
                try {
                    town.setHasUpkeep(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("hasUnlimitedClaims");
            if (line != null)
                try {
                    town.setHasUnlimitedClaims(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("taxpercent");
            if (line != null)
                try {
                    town.setTaxPercentage(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("maxPercentTaxAmount");
            if (line != null)
                town.setMaxPercentTaxAmount(Double.parseDouble(line));
            else
                town.setMaxPercentTaxAmount(TownySettings.getMaxTownTaxPercentAmount());
            line = keys.get("taxes");
            if (line != null)
                try {
                    town.setTaxes(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setTaxes(0);
                }
            line = keys.get("plotTax");
            if (line != null)
                try {
                    town.setPlotTax(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setPlotTax(0);
                }
            line = keys.get("commercialPlotPrice");
            if (line != null)
                try {
                    town.setCommercialPlotPrice(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setCommercialPlotPrice(0);
                }
            line = keys.get("commercialPlotTax");
            if (line != null)
                try {
                    town.setCommercialPlotTax(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setCommercialPlotTax(0);
                }
            line = keys.get("embassyPlotPrice");
            if (line != null)
                try {
                    town.setEmbassyPlotPrice(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setEmbassyPlotPrice(0);
                }
            line = keys.get("embassyPlotTax");
            if (line != null)
                try {
                    town.setEmbassyPlotTax(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setEmbassyPlotTax(0);
                }
            line = keys.get("spawnCost");
            if (line != null)
                try {
                    town.setSpawnCost(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setSpawnCost(TownySettings.getSpawnTravelCost());
                }
            line = keys.get("adminDisabledPvP");
            if (line != null)
                try {
                    town.setAdminDisabledPVP(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("adminEnabledPvP");
            if (line != null)
                try {
                    town.setAdminEnabledPVP(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("open");
            if (line != null)
                try {
                    town.setOpen(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("public");
            if (line != null)
                try {
                    town.setPublic(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("conquered");
            if (line != null)
                try {
                    town.setConquered(Boolean.parseBoolean(line));
                } catch (Exception ignored) {
                }
            line = keys.get("conqueredDays");
            if (line != null)
                town.setConqueredDays(Integer.parseInt(line));
            line = keys.get("joinedNationAt");
            if (line != null)
                try {
                    town.setJoinedNationAt(Long.parseLong(line));
                } catch (Exception ignored) {
                }
            line = keys.get("movedHomeBlockAt");
            if (line != null)
                try {
                    town.setMovedHomeBlockAt(Long.parseLong(line));
                } catch (Exception ignored) {
                }
            line = keys.get("homeBlock");
            if (line != null) {
                tokens = line.split(",");
                if (tokens.length == 3) {
                    TownyWorld world = universe.getWorld(tokens[0]);
                    if (world == null)
                        TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_homeblock_load_invalid_world", town.getName()));
                    else {
                        try {
                            int x = Integer.parseInt(tokens[1]);
                            int z = Integer.parseInt(tokens[2]);
                            TownBlock homeBlock = universe.getTownBlock(new WorldCoord(world.getName(), x, z));
                            town.forceSetHomeBlock(homeBlock);
                        } catch (NumberFormatException e) {
                            TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_homeblock_load_invalid_location", town.getName()));
                        } catch (NotRegisteredException e) {
                            TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_homeblock_load_invalid_townblock", town.getName()));
                        } catch (TownyException e) {
                            TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_town_homeblock_not_exist", town.getName()));
                        }
                    }
                }
            }
            line = keys.get("spawn");
            if (line != null) {
                tokens = line.split(",");
                if (tokens.length >= 4)
                    try {
                        World world = plugin.getServerWorld(tokens[0]);
                        double x = Double.parseDouble(tokens[1]);
                        double y = Double.parseDouble(tokens[2]);
                        double z = Double.parseDouble(tokens[3]);
                        Location loc = new Location(world, x, y, z);
                        if (tokens.length == 6) {
                            loc.setPitch(Float.parseFloat(tokens[4]));
                            loc.setYaw(Float.parseFloat(tokens[5]));
                        }
                        town.setSpawn(loc);
                    } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                    }
            }
            // Load outpost spawns
            line = keys.get("outpostspawns");
            if (line != null) {
                String[] outposts = line.split(";");
                for (String spawn : outposts) {
                    tokens = spawn.split(",");
                    if (tokens.length >= 4)
                        try {
                            World world = plugin.getServerWorld(tokens[0]);
                            double x = Double.parseDouble(tokens[1]);
                            double y = Double.parseDouble(tokens[2]);
                            double z = Double.parseDouble(tokens[3]);
                            Location loc = new Location(world, x, y, z);
                            if (tokens.length == 6) {
                                loc.setPitch(Float.parseFloat(tokens[4]));
                                loc.setYaw(Float.parseFloat(tokens[5]));
                            }
                            town.forceAddOutpostSpawn(loc);
                        } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                        }
                }
            }
            // Load legacy jail spawns into new Jail objects.
            line = keys.get("jailspawns");
            if (line != null) {
                String[] jails = line.split(";");
                for (String spawn : jails) {
                    tokens = spawn.split(",");
                    if (tokens.length >= 4)
                        try {
                            World world = plugin.getServerWorld(tokens[0]);
                            double x = Double.parseDouble(tokens[1]);
                            double y = Double.parseDouble(tokens[2]);
                            double z = Double.parseDouble(tokens[3]);
                            Location loc = new Location(world, x, y, z);
                            if (tokens.length == 6) {
                                loc.setPitch(Float.parseFloat(tokens[4]));
                                loc.setYaw(Float.parseFloat(tokens[5]));
                            }
                            TownBlock tb = universe.getTownBlock(WorldCoord.parseWorldCoord(loc));
                            if (tb == null)
                                continue;
                            Jail jail = new Jail(UUID.randomUUID(), town, tb, new ArrayList<>(Collections.singleton(loc)));
                            universe.registerJail(jail);
                            town.addJail(jail);
                            tb.setJail(jail);
                            jail.save();
                        } catch (NumberFormatException | NullPointerException | NotRegisteredException ignored) {
                        }
                }
            }
            line = keys.get("uuid");
            if (line != null) {
                UUID townUUID = null;
                try {
                    townUUID = UUID.fromString(line);
                } catch (IllegalArgumentException ee) {
                    townUUID = UUID.randomUUID();
                }
                town.setUUID(townUUID);
                universe.registerTownUUID(town);
            }
            line = keys.get("registered");
            if (line != null) {
                try {
                    town.setRegistered(Long.parseLong(line));
                } catch (Exception ee) {
                    town.setRegistered(0);
                }
            }
            line = keys.get("metadata");
            if (line != null && !line.isEmpty())
                MetadataLoader.getInstance().deserializeMetadata(town, line.trim());
            line = keys.get("nation");
            if (line != null && !line.isEmpty()) {
                Nation nation = null;
                if (universe.hasNation(line))
                    nation = universe.getNation(line);
                else if (universe.getReplacementNameMap().containsKey(line))
                    nation = universe.getNation(universe.getReplacementNameMap().get(line));
                // Only set the nation if it exists
                if (nation != null)
                    town.setNation(nation, false);
            }
            line = keys.get("ruined");
            if (line != null)
                try {
                    town.setRuined(Boolean.parseBoolean(line));
                } catch (Exception e) {
                    town.setRuined(false);
                }
            line = keys.get("ruinedTime");
            if (line != null)
                try {
                    town.setRuinedTime(Long.parseLong(line));
                } catch (Exception ee) {
                    town.setRuinedTime(0);
                }
            line = keys.get("neutral");
            if (line != null)
                town.setNeutral(Boolean.parseBoolean(line));
            line = keys.get("debtBalance");
            if (line != null)
                try {
                    town.setDebtBalance(Double.parseDouble(line));
                } catch (Exception e) {
                    town.setDebtBalance(0.0);
                }
            line = keys.get("primaryJail");
            if (line != null) {
                UUID uuid = UUID.fromString(line);
                if (universe.hasJail(uuid))
                    town.setPrimaryJail(universe.getJail(uuid));
            }
            line = keys.get("trustedResidents");
            if (line != null && !line.isEmpty()) {
                for (Resident resident : TownyAPI.getInstance().getResidents(toUUIDArray(line.split(",")))) town.addTrustedResident(resident);
            }
            line = keys.get("mapColorHexCode");
            if (line != null) {
                try {
                    town.setMapColorHexCode(line);
                } catch (Exception e) {
                    town.setMapColorHexCode(MapUtil.generateRandomTownColourAsHexCode());
                }
            } else {
                town.setMapColorHexCode(MapUtil.generateRandomTownColourAsHexCode());
            }
            line = keys.get("nationZoneOverride");
            if (line != null)
                try {
                    town.setNationZoneOverride(Integer.parseInt(line));
                } catch (Exception ignored) {
                }
            line = keys.get("nationZoneEnabled");
            if (line != null)
                town.setNationZoneEnabled(Boolean.parseBoolean(line));
            line = keys.get("allies");
            if (line != null && !line.isEmpty()) {
                List<UUID> uuids = Arrays.stream(line.split(",")).map(uuid -> UUID.fromString(uuid)).collect(Collectors.toList());
                town.loadAllies(TownyAPI.getInstance().getTowns(uuids));
            }
            line = keys.get("enemies");
            if (line != null && !line.isEmpty()) {
                List<UUID> uuids = Arrays.stream(line.split(",")).map(uuid -> UUID.fromString(uuid)).collect(Collectors.toList());
                town.loadEnemies(TownyAPI.getInstance().getTowns(uuids));
            }
        } catch (Exception e) {
            TownyMessaging.sendErrorMsg(Translation.of("flatfile_err_reading_town_file_at_line", town.getName(), line, town.getName()));
            e.printStackTrace();
            return false;
        } finally {
            saveTown(town);
        }
        return true;
    } else {
        return false;
    }
}
Also used : Nation(com.palmergames.bukkit.towny.object.Nation) Translation(com.palmergames.bukkit.towny.object.Translation) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) Arrays(java.util.Arrays) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) Resident(com.palmergames.bukkit.towny.object.Resident) EmptyNationException(com.palmergames.bukkit.towny.exceptions.EmptyNationException) TownBlockTypeHandler(com.palmergames.bukkit.towny.object.TownBlockTypeHandler) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TownyUniverse(com.palmergames.bukkit.towny.TownyUniverse) ArrayList(java.util.ArrayList) DeleteFileTask(com.palmergames.bukkit.towny.tasks.DeleteFileTask) Location(org.bukkit.Location) Gson(com.google.gson.Gson) PlotGroup(com.palmergames.bukkit.towny.object.PlotGroup) World(org.bukkit.World) Map(java.util.Map) PermissionData(com.palmergames.bukkit.towny.object.PermissionData) Town(com.palmergames.bukkit.towny.object.Town) InvalidNameException(com.palmergames.bukkit.towny.exceptions.InvalidNameException) StringMgmt(com.palmergames.util.StringMgmt) Nation(com.palmergames.bukkit.towny.object.Nation) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) FileInputStream(java.io.FileInputStream) UUID(java.util.UUID) MapUtil(com.palmergames.bukkit.towny.utils.MapUtil) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) TownyAPI(com.palmergames.bukkit.towny.TownyAPI) MetadataLoader(com.palmergames.bukkit.towny.object.metadata.MetadataLoader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Towny(com.palmergames.bukkit.towny.Towny) TownyMessaging(com.palmergames.bukkit.towny.TownyMessaging) TownySettings(com.palmergames.bukkit.towny.TownySettings) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) FileMgmt(com.palmergames.util.FileMgmt) Collections(java.util.Collections) Jail(com.palmergames.bukkit.towny.object.jail.Jail) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) ArrayList(java.util.ArrayList) World(org.bukkit.World) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) NotRegisteredException(com.palmergames.bukkit.towny.exceptions.NotRegisteredException) EmptyNationException(com.palmergames.bukkit.towny.exceptions.EmptyNationException) InvalidNameException(com.palmergames.bukkit.towny.exceptions.InvalidNameException) AlreadyRegisteredException(com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) TownyException(com.palmergames.bukkit.towny.exceptions.TownyException) WorldCoord(com.palmergames.bukkit.towny.object.WorldCoord) Resident(com.palmergames.bukkit.towny.object.Resident) Jail(com.palmergames.bukkit.towny.object.jail.Jail) TownyWorld(com.palmergames.bukkit.towny.object.TownyWorld) UUID(java.util.UUID) File(java.io.File) TownBlock(com.palmergames.bukkit.towny.object.TownBlock) Location(org.bukkit.Location)

Aggregations

Jail (com.palmergames.bukkit.towny.object.jail.Jail)9 TownyException (com.palmergames.bukkit.towny.exceptions.TownyException)6 AlreadyRegisteredException (com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException)5 NotRegisteredException (com.palmergames.bukkit.towny.exceptions.NotRegisteredException)5 Resident (com.palmergames.bukkit.towny.object.Resident)5 Town (com.palmergames.bukkit.towny.object.Town)5 TownBlock (com.palmergames.bukkit.towny.object.TownBlock)5 TownyWorld (com.palmergames.bukkit.towny.object.TownyWorld)5 WorldCoord (com.palmergames.bukkit.towny.object.WorldCoord)5 ArrayList (java.util.ArrayList)5 Location (org.bukkit.Location)5 Towny (com.palmergames.bukkit.towny.Towny)4 TownyAPI (com.palmergames.bukkit.towny.TownyAPI)4 TownyMessaging (com.palmergames.bukkit.towny.TownyMessaging)4 TownySettings (com.palmergames.bukkit.towny.TownySettings)4 TownyUniverse (com.palmergames.bukkit.towny.TownyUniverse)4 Nation (com.palmergames.bukkit.towny.object.Nation)4 PlotGroup (com.palmergames.bukkit.towny.object.PlotGroup)4 FileMgmt (com.palmergames.util.FileMgmt)4 File (java.io.File)4