Search in sources :

Example 1 with FlagParseException

use of com.plotsquared.core.plot.flag.FlagParseException in project PlotSquared by IntellectualSites.

the class SQLManager method getPlots.

/**
 * Load all plots, helpers, denied, trusted, and every setting from DB into a {@link HashMap}.
 */
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlots() {
    HashMap<String, HashMap<PlotId, Plot>> newPlots = new HashMap<>();
    HashMap<Integer, Plot> plots = new HashMap<>();
    try {
        HashSet<String> areas = new HashSet<>();
        if (this.worldConfiguration.contains("worlds")) {
            ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection("worlds");
            if (worldSection != null) {
                for (String worldKey : worldSection.getKeys(false)) {
                    areas.add(worldKey);
                    ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas");
                    if (areaSection != null) {
                        for (String areaKey : areaSection.getKeys(false)) {
                            String[] split = areaKey.split("(?<![;])-");
                            if (split.length == 3) {
                                areas.add(worldKey + ';' + split[0]);
                            }
                        }
                    }
                }
            }
        }
        HashMap<String, UUID> uuids = new HashMap<>();
        HashMap<String, AtomicInteger> noExist = new HashMap<>();
        /*
             * Getting plots
             */
        try (Statement statement = this.connection.createStatement()) {
            int id;
            String o;
            UUID user;
            try (ResultSet resultSet = statement.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world`, `timestamp` FROM `" + this.prefix + "plot`")) {
                ArrayList<Integer> toDelete = new ArrayList<>();
                while (resultSet.next()) {
                    PlotId plot_id = PlotId.of(resultSet.getInt("plot_id_x"), resultSet.getInt("plot_id_z"));
                    id = resultSet.getInt("id");
                    String areaID = resultSet.getString("world");
                    if (!areas.contains(areaID)) {
                        if (Settings.Enabled_Components.DATABASE_PURGER) {
                            toDelete.add(id);
                            continue;
                        } else {
                            AtomicInteger value = noExist.get(areaID);
                            if (value != null) {
                                value.incrementAndGet();
                            } else {
                                noExist.put(areaID, new AtomicInteger(1));
                            }
                        }
                    }
                    o = resultSet.getString("owner");
                    user = uuids.get(o);
                    if (user == null) {
                        try {
                            user = UUID.fromString(o);
                        } catch (IllegalArgumentException e) {
                            if (Settings.UUID.FORCE_LOWERCASE) {
                                user = UUID.nameUUIDFromBytes(("OfflinePlayer:" + o.toLowerCase()).getBytes(Charsets.UTF_8));
                            } else {
                                user = UUID.nameUUIDFromBytes(("OfflinePlayer:" + o).getBytes(Charsets.UTF_8));
                            }
                        }
                        uuids.put(o, user);
                    }
                    long time;
                    try {
                        Timestamp timestamp = resultSet.getTimestamp("timestamp");
                        time = timestamp.getTime();
                    } catch (SQLException exception) {
                        String parsable = resultSet.getString("timestamp");
                        try {
                            time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(parsable).getTime();
                        } catch (ParseException e) {
                            LOGGER.error("Could not parse date for plot: #{}({};{}) ({})", id, areaID, plot_id, parsable);
                            time = System.currentTimeMillis() + id;
                        }
                    }
                    Plot p = new Plot(plot_id, user, new HashSet<>(), new HashSet<>(), new HashSet<>(), "", null, null, null, new boolean[] { false, false, false, false }, time, id);
                    HashMap<PlotId, Plot> map = newPlots.get(areaID);
                    if (map != null) {
                        Plot last = map.put(p.getId(), p);
                        if (last != null) {
                            if (Settings.Enabled_Components.DATABASE_PURGER) {
                                toDelete.add(last.temp);
                            } else {
                                LOGGER.info("Plot #{}({}) in `{}plot` is a duplicate." + " Delete this plot or set `database-purger: true` in the settings.yml", id, last, this.prefix);
                            }
                        }
                    } else {
                        map = new HashMap<>();
                        newPlots.put(areaID, map);
                        map.put(p.getId(), p);
                    }
                    plots.put(id, p);
                }
                deleteRows(toDelete, this.prefix + "plot", "id");
            }
            if (Settings.Enabled_Components.RATING_CACHE) {
                try (ResultSet r = statement.executeQuery("SELECT `plot_plot_id`, `player`, `rating` FROM `" + this.prefix + "plot_rating`")) {
                    ArrayList<Integer> toDelete = new ArrayList<>();
                    while (r.next()) {
                        id = r.getInt("plot_plot_id");
                        o = r.getString("player");
                        user = uuids.get(o);
                        if (user == null) {
                            user = UUID.fromString(o);
                            uuids.put(o, user);
                        }
                        Plot plot = plots.get(id);
                        if (plot != null) {
                            plot.getSettings().getRatings().put(user, r.getInt("rating"));
                        } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                            toDelete.add(id);
                        } else {
                            LOGGER.warn("Entry #{}({}) in `plot_rating` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                        }
                    }
                    deleteRows(toDelete, this.prefix + "plot_rating", "plot_plot_id");
                }
            }
            /*
                 * Getting helpers
                 */
            try (ResultSet r = statement.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + this.prefix + "plot_helpers`")) {
                ArrayList<Integer> toDelete = new ArrayList<>();
                while (r.next()) {
                    id = r.getInt("plot_plot_id");
                    o = r.getString("user_uuid");
                    user = uuids.get(o);
                    if (user == null) {
                        user = UUID.fromString(o);
                        uuids.put(o, user);
                    }
                    Plot plot = plots.get(id);
                    if (plot != null) {
                        plot.getTrusted().add(user);
                    } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                        toDelete.add(id);
                    } else {
                        LOGGER.warn("Entry #{}({}) in `plot_helpers` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                    }
                }
                deleteRows(toDelete, this.prefix + "plot_helpers", "plot_plot_id");
            }
            /*
                 * Getting trusted
                 */
            try (ResultSet r = statement.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + this.prefix + "plot_trusted`")) {
                ArrayList<Integer> toDelete = new ArrayList<>();
                while (r.next()) {
                    id = r.getInt("plot_plot_id");
                    o = r.getString("user_uuid");
                    user = uuids.get(o);
                    if (user == null) {
                        user = UUID.fromString(o);
                        uuids.put(o, user);
                    }
                    Plot plot = plots.get(id);
                    if (plot != null) {
                        plot.getMembers().add(user);
                    } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                        toDelete.add(id);
                    } else {
                        LOGGER.warn("Entry #{}({}) in `plot_trusted` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                    }
                }
                deleteRows(toDelete, this.prefix + "plot_trusted", "plot_plot_id");
            }
            /*
                 * Getting denied
                 */
            try (ResultSet r = statement.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + this.prefix + "plot_denied`")) {
                ArrayList<Integer> toDelete = new ArrayList<>();
                while (r.next()) {
                    id = r.getInt("plot_plot_id");
                    o = r.getString("user_uuid");
                    user = uuids.get(o);
                    if (user == null) {
                        user = UUID.fromString(o);
                        uuids.put(o, user);
                    }
                    Plot plot = plots.get(id);
                    if (plot != null) {
                        plot.getDenied().add(user);
                    } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                        toDelete.add(id);
                    } else {
                        LOGGER.warn("Entry #{}({}) in `plot_denied` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                    }
                }
                deleteRows(toDelete, this.prefix + "plot_denied", "plot_plot_id");
            }
            try (final ResultSet resultSet = statement.executeQuery("SELECT * FROM `" + this.prefix + "plot_flags`")) {
                BlockTypeListFlag.skipCategoryVerification = // allow invalid tags, as initialized lazily
                true;
                final ArrayList<Integer> toDelete = new ArrayList<>();
                final Map<Plot, Collection<PlotFlag<?, ?>>> invalidFlags = new HashMap<>();
                while (resultSet.next()) {
                    id = resultSet.getInt("plot_id");
                    final String flag = resultSet.getString("flag");
                    String value = resultSet.getString("value");
                    final Plot plot = plots.get(id);
                    if (plot != null) {
                        final PlotFlag<?, ?> plotFlag = GlobalFlagContainer.getInstance().getFlagFromString(flag);
                        if (plotFlag == null) {
                            plot.getFlagContainer().addUnknownFlag(flag, value);
                        } else {
                            value = CaptionUtility.stripClickEvents(plotFlag, value);
                            try {
                                plot.getFlagContainer().addFlag(plotFlag.parse(value));
                            } catch (final FlagParseException e) {
                                e.printStackTrace();
                                LOGGER.error("Plot with ID {} has an invalid value:", id);
                                LOGGER.error("Failed to parse flag '{}', value '{}': {}", plotFlag.getName(), e.getValue(), e.getErrorMessage());
                                if (!invalidFlags.containsKey(plot)) {
                                    invalidFlags.put(plot, new ArrayList<>());
                                }
                                invalidFlags.get(plot).add(plotFlag);
                            }
                        }
                    } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                        toDelete.add(id);
                    } else {
                        LOGGER.warn("Entry #{}({}) in `plot_flags` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                    }
                }
                BlockTypeListFlag.skipCategoryVerification = // don't allow invalid tags anymore
                false;
                if (Settings.Enabled_Components.DATABASE_PURGER) {
                    for (final Map.Entry<Plot, Collection<PlotFlag<?, ?>>> plotFlagEntry : invalidFlags.entrySet()) {
                        for (final PlotFlag<?, ?> flag : plotFlagEntry.getValue()) {
                            LOGGER.info("Plot {} has an invalid flag ({}). A fix has been attempted", plotFlagEntry.getKey(), flag.getName());
                            removeFlag(plotFlagEntry.getKey(), flag);
                        }
                    }
                }
                deleteRows(toDelete, this.prefix + "plot_flags", "plot_id");
            }
            try (ResultSet resultSet = statement.executeQuery("SELECT * FROM `" + this.prefix + "plot_settings`")) {
                ArrayList<Integer> toDelete = new ArrayList<>();
                while (resultSet.next()) {
                    id = resultSet.getInt("plot_plot_id");
                    Plot plot = plots.get(id);
                    if (plot != null) {
                        plots.remove(id);
                        String alias = resultSet.getString("alias");
                        if (alias != null) {
                            plot.getSettings().setAlias(alias);
                        }
                        String pos = resultSet.getString("position");
                        switch(pos.toLowerCase()) {
                            case "":
                            case "default":
                            case "0,0,0":
                            case "center":
                            case "centre":
                                break;
                            default:
                                try {
                                    plot.getSettings().setPosition(BlockLoc.fromString(pos));
                                } catch (Exception ignored) {
                                }
                        }
                        int m = resultSet.getInt("merged");
                        boolean[] merged = new boolean[4];
                        for (int i = 0; i < 4; i++) {
                            merged[3 - i] = (m & 1 << i) != 0;
                        }
                        plot.getSettings().setMerged(merged);
                    } else if (Settings.Enabled_Components.DATABASE_PURGER) {
                        toDelete.add(id);
                    } else {
                        LOGGER.warn("Entry #{}({}) in `plot_settings` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot);
                    }
                }
                deleteRows(toDelete, this.prefix + "plot_settings", "plot_plot_id");
            }
        }
        if (!plots.entrySet().isEmpty()) {
            createEmptySettings(new ArrayList<>(plots.keySet()), null);
            for (Entry<Integer, Plot> entry : plots.entrySet()) {
                entry.getValue().getSettings();
            }
        }
        boolean invalidPlot = false;
        for (Entry<String, AtomicInteger> entry : noExist.entrySet()) {
            String worldName = entry.getKey();
            invalidPlot = true;
            if (Settings.DEBUG) {
                LOGGER.info("Warning! Found {} plots in DB for non existent world: '{}'", entry.getValue().intValue(), worldName);
            }
        }
        if (invalidPlot && Settings.DEBUG) {
            LOGGER.info("Warning! Please create the world(s) or remove the plots using the purge command");
        }
    } catch (SQLException e) {
        LOGGER.error("Failed to load plots", e);
    }
    return newPlots;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) PlotId(com.plotsquared.core.plot.PlotId) ResultSet(java.sql.ResultSet) UUID(java.util.UUID) HashSet(java.util.HashSet) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Plot(com.plotsquared.core.plot.Plot) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SQLException(java.sql.SQLException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Collection(java.util.Collection) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SimpleDateFormat(java.text.SimpleDateFormat) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ConfigurationSection(com.plotsquared.core.configuration.ConfigurationSection)

Example 2 with FlagParseException

use of com.plotsquared.core.plot.flag.FlagParseException in project PlotSquared by IntellectualSites.

the class BlockTypeListFlag method getCategory.

private BlockTypeWrapper getCategory(final String blockString) throws FlagParseException {
    if (!blockString.startsWith("#")) {
        throw new FlagParseException(this, blockString, TranslatableCaption.of("flags.flag_error_invalid_block"));
    }
    String categoryId = blockString.substring(1);
    BlockTypeWrapper blockTypeWrapper;
    if (skipCategoryVerification) {
        blockTypeWrapper = BlockTypeWrapper.get(categoryId);
    } else {
        BlockCategory blockCategory = BlockCategory.REGISTRY.get(categoryId);
        if (blockCategory == null) {
            throw new FlagParseException(this, blockString, TranslatableCaption.of("flags.flag_error_invalid_block"));
        }
        blockTypeWrapper = BlockTypeWrapper.get(blockCategory);
    }
    return blockTypeWrapper;
}
Also used : FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) BlockCategory(com.sk89q.worldedit.world.block.BlockCategory)

Example 3 with FlagParseException

use of com.plotsquared.core.plot.flag.FlagParseException in project PlotSquared by IntellectualSites.

the class PlotTitleFlag method parse.

@Override
public PlotTitleFlag parse(@NonNull String input) throws FlagParseException {
    if (input.equals("CONFIGURED")) {
        return TITLE_FLAG_DEFAULT;
    }
    if (!input.contains("\"")) {
        return new PlotTitleFlag(new PlotTitle(input, ""));
    }
    var split = StringMan.splitMessage(input);
    if (split.isEmpty() || split.size() > 2) {
        throw new FlagParseException(this, input, TranslatableCaption.of("flags.flag_error_title"));
    }
    PlotTitle value;
    if (split.size() == 1) {
        value = new PlotTitle(split.get(0), "");
    } else {
        value = new PlotTitle(split.get(0), split.get(1));
    }
    return new PlotTitleFlag(value);
}
Also used : FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) PlotTitle(com.plotsquared.core.plot.PlotTitle)

Example 4 with FlagParseException

use of com.plotsquared.core.plot.flag.FlagParseException in project PlotSquared by IntellectualSites.

the class TimedFlag method parse.

@Override
public F parse(@NonNull String input) throws FlagParseException {
    String[] split = input.split(" ", 2);
    int interval;
    try {
        interval = Integer.parseInt(split[0]);
    } catch (Throwable throwable) {
        throw new FlagParseException(this, input, TranslatableCaption.of("flags.flag_error_integer"));
    }
    if (interval < 1) {
        throw new FlagParseException(this, input, TranslatableCaption.of("flags.flag_error_integer"));
    }
    if (split.length == 1) {
        return flagOf(new Timed<>(interval, defaultValue));
    }
    final T parsedValue = parseValue(split[1]);
    return flagOf(new Timed<>(interval, parsedValue));
}
Also used : FlagParseException(com.plotsquared.core.plot.flag.FlagParseException)

Aggregations

FlagParseException (com.plotsquared.core.plot.flag.FlagParseException)4 ConfigurationSection (com.plotsquared.core.configuration.ConfigurationSection)1 Plot (com.plotsquared.core.plot.Plot)1 PlotId (com.plotsquared.core.plot.PlotId)1 PlotTitle (com.plotsquared.core.plot.PlotTitle)1 BlockCategory (com.sk89q.worldedit.world.block.BlockCategory)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Statement (java.sql.Statement)1 Timestamp (java.sql.Timestamp)1 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 UUID (java.util.UUID)1