Search in sources :

Example 1 with PlotId

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

the class SearchPlotProvider method getPlotsBySearch.

/**
 * Fuzzy plot search with spaces separating terms.
 * - Terms: type, alias, world, owner, trusted, member
 *
 * @param search Search string
 * @return Search results
 */
@NonNull
private static List<Plot> getPlotsBySearch(@NonNull final String search) {
    String[] split = search.split(" ");
    int size = split.length * 2;
    List<UUID> uuids = new ArrayList<>();
    PlotId id = null;
    for (String term : split) {
        try {
            UUID uuid = PlotSquared.get().getImpromptuUUIDPipeline().getSingle(term, Settings.UUID.BLOCKING_TIMEOUT);
            if (uuid == null) {
                uuid = UUID.fromString(term);
            }
            uuids.add(uuid);
        } catch (Exception ignored) {
            id = PlotId.fromString(term);
        }
    }
    ArrayList<ArrayList<Plot>> plotList = IntStream.range(0, size).mapToObj(i -> new ArrayList<Plot>()).collect(Collectors.toCollection(() -> new ArrayList<>(size)));
    PlotArea area = null;
    String alias = null;
    for (Plot plot : PlotQuery.newQuery().allPlots()) {
        int count = 0;
        if (!uuids.isEmpty()) {
            for (UUID uuid : uuids) {
                if (plot.isOwner(uuid)) {
                    count += 2;
                } else if (plot.isAdded(uuid)) {
                    count++;
                }
            }
        }
        if (id != null) {
            if (plot.getId().equals(id)) {
                count++;
            }
        }
        if (area != null && plot.getArea().equals(area)) {
            count++;
        }
        if (alias != null && alias.equals(plot.getAlias())) {
            count += 2;
        }
        if (count != 0) {
            plotList.get(count - 1).add(plot);
        }
    }
    List<Plot> plots = new ArrayList<>();
    for (int i = plotList.size() - 1; i >= 0; i--) {
        if (!plotList.get(i).isEmpty()) {
            plots.addAll(plotList.get(i));
        }
    }
    return plots;
}
Also used : IntStream(java.util.stream.IntStream) NonNull(org.checkerframework.checker.nullness.qual.NonNull) List(java.util.List) PlotSquared(com.plotsquared.core.PlotSquared) Plot(com.plotsquared.core.plot.Plot) Collection(java.util.Collection) PlotId(com.plotsquared.core.plot.PlotId) Settings(com.plotsquared.core.configuration.Settings) UUID(java.util.UUID) PlotArea(com.plotsquared.core.plot.PlotArea) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) PlotArea(com.plotsquared.core.plot.PlotArea) Plot(com.plotsquared.core.plot.Plot) ArrayList(java.util.ArrayList) PlotId(com.plotsquared.core.plot.PlotId) UUID(java.util.UUID) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 2 with PlotId

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

the class Save method onCommand.

@Override
public boolean onCommand(final PlotPlayer<?> player, final String[] args) {
    final String world = player.getLocation().getWorldName();
    if (!this.plotAreaManager.hasPlotArea(world)) {
        player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
        return false;
    }
    final Plot plot = player.getCurrentPlot();
    if (plot == null) {
        player.sendMessage(TranslatableCaption.of("errors.not_in_plot"));
        return false;
    }
    if (!plot.hasOwner()) {
        player.sendMessage(TranslatableCaption.of("info.plot_unowned"));
        return false;
    }
    if (plot.getVolume() > Integer.MAX_VALUE) {
        player.sendMessage(TranslatableCaption.of("schematics.schematic_too_large"));
        return false;
    }
    if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, Permission.PERMISSION_ADMIN_COMMAND_SAVE)) {
        player.sendMessage(TranslatableCaption.of("permission.no_plot_perms"));
        return false;
    }
    if (plot.getRunning() > 0) {
        player.sendMessage(TranslatableCaption.of("errors.wait_for_timer"));
        return false;
    }
    plot.addRunning();
    this.schematicHandler.getCompoundTag(plot).whenComplete((compoundTag, throwable) -> {
        TaskManager.runTaskAsync(() -> {
            String time = (System.currentTimeMillis() / 1000) + "";
            Location[] corners = plot.getCorners();
            corners[0] = corners[0].withY(plot.getArea().getMinBuildHeight());
            corners[1] = corners[1].withY(plot.getArea().getMaxBuildHeight());
            int size = (corners[1].getX() - corners[0].getX()) + 1;
            PlotId id = plot.getId();
            String world1 = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", "");
            final String file = time + '_' + world1 + '_' + id.getX() + '_' + id.getY() + '_' + size;
            UUID uuid = player.getUUID();
            schematicHandler.upload(compoundTag, uuid, file, new RunnableVal<>() {

                @Override
                public void run(URL url) {
                    plot.removeRunning();
                    if (url == null) {
                        player.sendMessage(TranslatableCaption.of("backups.backup_save_failed"));
                        return;
                    }
                    player.sendMessage(TranslatableCaption.of("web.save_success"));
                    player.sendMessage(TranslatableCaption.of("errors.deprecated_commands"), Template.of("replacement", "/plot download"));
                    try (final MetaDataAccess<List<String>> schematicAccess = player.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_SCHEMATICS)) {
                        schematicAccess.get().ifPresent(schematics -> schematics.add(file + ".schem"));
                    }
                }
            });
        });
    });
    return true;
}
Also used : Location(com.plotsquared.core.location.Location) MetaDataAccess(com.plotsquared.core.player.MetaDataAccess) Permissions(com.plotsquared.core.util.Permissions) NonNull(org.checkerframework.checker.nullness.qual.NonNull) Plot(com.plotsquared.core.plot.Plot) PlotAreaManager(com.plotsquared.core.plot.world.PlotAreaManager) RunnableVal(com.plotsquared.core.util.task.RunnableVal) URL(java.net.URL) Inject(com.google.inject.Inject) TaskManager(com.plotsquared.core.util.task.TaskManager) PlotId(com.plotsquared.core.plot.PlotId) Permission(com.plotsquared.core.permissions.Permission) UUID(java.util.UUID) List(java.util.List) PlotPlayer(com.plotsquared.core.player.PlotPlayer) SchematicHandler(com.plotsquared.core.util.SchematicHandler) TranslatableCaption(com.plotsquared.core.configuration.caption.TranslatableCaption) PlayerMetaDataKeys(com.plotsquared.core.player.PlayerMetaDataKeys) Template(net.kyori.adventure.text.minimessage.Template) PlotId(com.plotsquared.core.plot.PlotId) Plot(com.plotsquared.core.plot.Plot) UUID(java.util.UUID) MetaDataAccess(com.plotsquared.core.player.MetaDataAccess) URL(java.net.URL) Location(com.plotsquared.core.location.Location)

Example 3 with PlotId

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

the class SQLManager method createPlotsAndData.

@Override
public void createPlotsAndData(final List<Plot> myList, final Runnable whenDone) {
    addGlobalTask(() -> {
        try {
            // Create the plots
            createPlots(myList, () -> {
                final Map<PlotId, Integer> idMap = new HashMap<>();
                try {
                    // Creating datastructures
                    HashMap<PlotId, Plot> plotMap = new HashMap<>();
                    for (Plot plot : myList) {
                        plotMap.put(plot.getId(), plot);
                    }
                    ArrayList<LegacySettings> settings = new ArrayList<>();
                    final ArrayList<UUIDPair> helpers = new ArrayList<>();
                    final ArrayList<UUIDPair> trusted = new ArrayList<>();
                    final ArrayList<UUIDPair> denied = new ArrayList<>();
                    // Populating structures
                    try (PreparedStatement stmt = SQLManager.this.connection.prepareStatement(SQLManager.this.GET_ALL_PLOTS);
                        ResultSet result = stmt.executeQuery()) {
                        while (result.next()) {
                            int id = result.getInt("id");
                            int x = result.getInt("plot_id_x");
                            int y = result.getInt("plot_id_z");
                            PlotId plotId = PlotId.of(x, y);
                            Plot plot = plotMap.get(plotId);
                            idMap.put(plotId, id);
                            if (plot != null) {
                                settings.add(new LegacySettings(id, plot.getSettings()));
                                for (UUID uuid : plot.getDenied()) {
                                    denied.add(new UUIDPair(id, uuid));
                                }
                                for (UUID uuid : plot.getMembers()) {
                                    trusted.add(new UUIDPair(id, uuid));
                                }
                                for (UUID uuid : plot.getTrusted()) {
                                    helpers.add(new UUIDPair(id, uuid));
                                }
                            }
                        }
                    }
                    createFlags(idMap, myList, () -> createSettings(settings, () -> createTiers(helpers, "helpers", () -> createTiers(trusted, "trusted", () -> createTiers(denied, "denied", () -> {
                        try {
                            SQLManager.this.connection.commit();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        if (whenDone != null) {
                            whenDone.run();
                        }
                    })))));
                } catch (SQLException e) {
                    LOGGER.warn("Failed to set all flags and member tiers for plots", e);
                    try {
                        SQLManager.this.connection.commit();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.warn("Warning! Failed to set all helper for plots", e);
            try {
                SQLManager.this.connection.commit();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    });
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) Plot(com.plotsquared.core.plot.Plot) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SQLException(java.sql.SQLException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PlotId(com.plotsquared.core.plot.PlotId) ResultSet(java.sql.ResultSet) UUID(java.util.UUID)

Example 4 with PlotId

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

the class SQLManager method getClusters.

@Override
public HashMap<String, Set<PlotCluster>> getClusters() {
    LinkedHashMap<String, Set<PlotCluster>> newClusters = new LinkedHashMap<>();
    HashMap<Integer, PlotCluster> clusters = 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, Integer> noExist = new HashMap<>();
        /*
             * Getting clusters
             */
        try (Statement stmt = this.connection.createStatement()) {
            ResultSet resultSet = stmt.executeQuery("SELECT * FROM `" + this.prefix + "cluster`");
            PlotCluster cluster;
            String owner;
            UUID user;
            int id;
            while (resultSet.next()) {
                PlotId pos1 = PlotId.of(resultSet.getInt("pos1_x"), resultSet.getInt("pos1_z"));
                PlotId pos2 = PlotId.of(resultSet.getInt("pos2_x"), resultSet.getInt("pos2_z"));
                id = resultSet.getInt("id");
                String areaid = resultSet.getString("world");
                if (!areas.contains(areaid)) {
                    noExist.merge(areaid, 1, Integer::sum);
                }
                owner = resultSet.getString("owner");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = new PlotCluster(null, pos1, pos2, user, id);
                clusters.put(id, cluster);
                Set<PlotCluster> set = newClusters.computeIfAbsent(areaid, k -> new HashSet<>());
                set.add(cluster);
            }
            // Getting helpers
            resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_helpers`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                owner = resultSet.getString("user_uuid");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = clusters.get(id);
                if (cluster != null) {
                    cluster.helpers.add(user);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            // Getting invited
            resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_invited`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                owner = resultSet.getString("user_uuid");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = clusters.get(id);
                if (cluster != null) {
                    cluster.invited.add(user);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            resultSet = stmt.executeQuery("SELECT * FROM `" + this.prefix + "cluster_settings`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                cluster = clusters.get(id);
                if (cluster != null) {
                    String alias = resultSet.getString("alias");
                    if (alias != null) {
                        cluster.settings.setAlias(alias);
                    }
                    String pos = resultSet.getString("position");
                    switch(pos.toLowerCase()) {
                        case "":
                        case "default":
                        case "0,0,0":
                        case "center":
                        case "centre":
                            break;
                        default:
                            try {
                                BlockLoc loc = BlockLoc.fromString(pos);
                                cluster.settings.setPosition(loc);
                            } 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;
                    }
                    cluster.settings.setMerged(merged);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            resultSet.close();
        }
        boolean invalidPlot = false;
        for (Entry<String, Integer> entry : noExist.entrySet()) {
            String a = entry.getKey();
            invalidPlot = true;
            LOGGER.warn("Warning! Found {} clusters in DB for non existent area; '{}'", noExist.get(a), a);
        }
        if (invalidPlot) {
            LOGGER.warn("Warning! Please create the world(s) or remove the clusters using the purge command");
        }
    } catch (SQLException e) {
        LOGGER.error("Failed to load clusters", e);
    }
    return newClusters;
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) LinkedHashMap(java.util.LinkedHashMap) PlotId(com.plotsquared.core.plot.PlotId) ResultSet(java.sql.ResultSet) UUID(java.util.UUID) HashSet(java.util.HashSet) PlotCluster(com.plotsquared.core.plot.PlotCluster) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) BlockLoc(com.plotsquared.core.location.BlockLoc) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SQLException(java.sql.SQLException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConfigurationSection(com.plotsquared.core.configuration.ConfigurationSection)

Example 5 with PlotId

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

the class SQLManager method swapPlots.

@Override
public CompletableFuture<Boolean> swapPlots(Plot plot1, Plot plot2) {
    final CompletableFuture<Boolean> future = new CompletableFuture<>();
    TaskManager.runTaskAsync(() -> {
        final int id1 = getId(plot1);
        final int id2 = getId(plot2);
        final PlotId pos1 = plot1.getId();
        final PlotId pos2 = plot2.getId();
        try (final PreparedStatement preparedStatement = this.connection.prepareStatement("UPDATE `" + SQLManager.this.prefix + "plot` SET `plot_id_x` = ?, `plot_id_z` = ? WHERE `id` = ?")) {
            preparedStatement.setInt(1, pos1.getX());
            preparedStatement.setInt(2, pos1.getY());
            preparedStatement.setInt(3, id1);
            preparedStatement.execute();
            preparedStatement.setInt(1, pos2.getX());
            preparedStatement.setInt(2, pos2.getY());
            preparedStatement.setInt(3, id2);
            preparedStatement.execute();
        } catch (final Exception e) {
            LOGGER.error("Failed to persist wap of {} and {}", plot1, plot2);
            e.printStackTrace();
            future.complete(false);
            return;
        }
        future.complete(true);
    });
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) PlotId(com.plotsquared.core.plot.PlotId) PreparedStatement(java.sql.PreparedStatement) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SQLException(java.sql.SQLException)

Aggregations

PlotId (com.plotsquared.core.plot.PlotId)18 Plot (com.plotsquared.core.plot.Plot)9 UUID (java.util.UUID)9 SQLException (java.sql.SQLException)7 PreparedStatement (java.sql.PreparedStatement)6 Location (com.plotsquared.core.location.Location)5 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 FlagParseException (com.plotsquared.core.plot.flag.FlagParseException)4 ResultSet (java.sql.ResultSet)4 ParseException (java.text.ParseException)4 ArrayList (java.util.ArrayList)4 LinkedHashMap (java.util.LinkedHashMap)4 List (java.util.List)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 PlotPlayer (com.plotsquared.core.player.PlotPlayer)3 PlotArea (com.plotsquared.core.plot.PlotArea)3 Collection (java.util.Collection)3 PlotSquared (com.plotsquared.core.PlotSquared)2