Merge branch 'v6' into feature/v6/json

# Conflicts:
#	Bukkit/build.gradle
#	Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java
#	Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java
#	Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java
#	Core/build.gradle
#	Core/src/main/java/com/plotsquared/core/PlotPlatform.java
#	Core/src/main/java/com/plotsquared/core/PlotSquared.java
#	Core/src/main/java/com/plotsquared/core/command/Add.java
#	Core/src/main/java/com/plotsquared/core/command/Area.java
#	Core/src/main/java/com/plotsquared/core/command/Auto.java
#	Core/src/main/java/com/plotsquared/core/command/Command.java
#	Core/src/main/java/com/plotsquared/core/command/ListCmd.java
#	Core/src/main/java/com/plotsquared/core/configuration/Caption.java
#	Core/src/main/java/com/plotsquared/core/listener/PlotListener.java
#	Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java
#	Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java
#	Core/src/main/java/com/plotsquared/core/plot/message/PlotMessage.java
#	Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java
#	Core/src/main/java/com/plotsquared/core/util/MainUtil.java
#	Core/src/main/java/com/plotsquared/core/util/WorldUtil.java
This commit is contained in:
Alexander Söderberg 2020-07-14 19:25:14 +02:00
commit 198bcfdf4d
No known key found for this signature in database
GPG Key ID: C0207FF7EA146678
332 changed files with 5743 additions and 4139 deletions

View File

@ -29,7 +29,7 @@ dependencies {
exclude(module: "bukkit")
}
compile("io.papermc:paperlib:1.0.2")
compile("io.papermc:paperlib:1.0.4")
implementation("net.kyori:text-adapter-bukkit:3.0.3")
compile("com.github.MilkBowl:VaultAPI:1.7") {
exclude(module: "bukkit")
@ -44,6 +44,8 @@ dependencies {
implementation('net.kyori:adventure-text-minimessage:3.0.0-SNAPSHOT')
compile("se.hyperver.hyperverse:Core:0.6.0-SNAPSHOT"){ transitive = false }
compile('com.sk89q:squirrelid:1.0.0-SNAPSHOT'){ transitive = false }
// logging
implementation('org.apache.logging.log4j:log4j-slf4j-impl:2.8.1')
}
sourceCompatibility = 1.8
@ -97,18 +99,28 @@ task copyFiles {
shadowJar {
dependencies {
include(dependency(":PlotSquared-Core"))
include(dependency("io.papermc:paperlib:1.0.2"))
include(dependency("io.papermc:paperlib:1.0.4"))
include(dependency("net.kyori:adventure-platform-bukkit:4.0.0-SNAPSHOT"))
include(dependency("net.kyori:adventure-text-minimessage:3.0.0-SNAPSHOT"))
include(dependency("org.bstats:bstats-bukkit:1.7"))
include(dependency("org.khelekore:prtree:1.7.0-SNAPSHOT"))
include(dependency("com.sk89q:squirrelid:1.0.0-SNAPSHOT"))
include(dependency("com.google.inject:guice:4.2.3"))
include(dependency("com.google.inject.extensions:guice-assistedinject:4.2.3"))
include(dependency("javax.annotation:javax-annotation-api"))
include(dependency('org.apache.logging.log4j:log4j-slf4j-impl'))
include(dependency('org.slf4j:slf4j-api'))
}
relocate('net.kyori.text', 'com.plotsquared.formatting.text')
relocate("io.papermc.lib", "com.plotsquared.bukkit.paperlib")
relocate("org.bstats", "com.plotsquared.metrics")
relocate('com.sk89q.squirrelid', 'com.plotsquared.squirrelid')
relocate('org.khelekore.prtree', 'com.plotsquared.prtree')
relocate('org.apache.logging.slf4j', 'com.plotsquared.logging.apache')
relocate('org.slf4j', 'com.plotsquared.logging.slf4j')
relocate('com.google.inject', 'com.plotsquared.google')
archiveFileName = "${project.name}-${parent.version}.jar"
destinationDirectory = file "../target"
}

View File

@ -12,6 +12,12 @@
<version>20200518</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
@ -176,6 +182,12 @@
<version>4.0-dev-106</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.8.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -25,17 +25,21 @@
*/
package com.plotsquared.bukkit;
import com.plotsquared.bukkit.generator.BukkitHybridUtils;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Stage;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.bukkit.inject.BackupModule;
import com.plotsquared.bukkit.inject.BukkitModule;
import com.plotsquared.bukkit.inject.WorldManagerModule;
import com.plotsquared.bukkit.listener.ChunkListener;
import com.plotsquared.bukkit.listener.EntitySpawnListener;
import com.plotsquared.bukkit.listener.PaperListener;
import com.plotsquared.bukkit.listener.PlayerEvents;
import com.plotsquared.bukkit.listener.SingleWorldListener;
import com.plotsquared.bukkit.listener.WorldEvents;
import com.plotsquared.bukkit.managers.BukkitWorldManager;
import com.plotsquared.bukkit.managers.HyperverseWorldManager;
import com.plotsquared.bukkit.managers.MultiverseWorldManager;
import com.plotsquared.bukkit.placeholder.PlaceholderFormatter;
import com.plotsquared.bukkit.placeholder.Placeholders;
import com.plotsquared.bukkit.player.BukkitPlayerManager;
@ -47,8 +51,10 @@ import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitPermHandler;
import com.plotsquared.bukkit.util.BukkitRegionManager;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitChatManager;
import com.plotsquared.bukkit.util.BukkitTaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitWorld;
import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.UpdateUtility;
import com.plotsquared.bukkit.uuid.BungeePermsUUIDService;
@ -58,57 +64,60 @@ import com.plotsquared.bukkit.uuid.OfflinePlayerUUIDService;
import com.plotsquared.bukkit.uuid.PaperUUIDService;
import com.plotsquared.bukkit.uuid.SQLiteUUIDService;
import com.plotsquared.bukkit.uuid.SquirrelIdUUIDService;
import com.plotsquared.core.IPlotMain;
import com.plotsquared.core.PlotPlatform;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.backup.NullBackupManager;
import com.plotsquared.core.backup.SimpleBackupManager;
import com.plotsquared.core.command.WE_Anywhere;
import com.plotsquared.core.components.ComponentPresetManager;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ChatFormatter;
import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.generator.HybridGen;
import com.plotsquared.core.generator.HybridUtils;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.generator.SingleWorldGenerator;
import com.plotsquared.core.inject.annotations.BackgroundPipeline;
import com.plotsquared.core.inject.annotations.DefaultGenerator;
import com.plotsquared.core.inject.annotations.ImpromptuPipeline;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.inject.modules.PlotSquaredModule;
import com.plotsquared.core.listener.PlotListener;
import com.plotsquared.core.listener.WESubscriber;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.comment.CommentManager;
import com.plotsquared.core.plot.message.PlainChatManager;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.queue.QueueProvider;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.setup.SettingsNodesWrapper;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.ChatManager;
import com.plotsquared.core.util.ConsoleColors;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.InventoryUtil;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.PermHandler;
import com.plotsquared.core.util.PlatformWorldManager;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.PremiumVerification;
import com.plotsquared.core.util.ReflectionUtils;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.uuid.CacheUUIDService;
import com.plotsquared.core.uuid.UUIDPipeline;
import com.plotsquared.core.uuid.offline.OfflineModeUUIDService;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extension.platform.Actor;
import io.papermc.lib.PaperLib;
import lombok.Getter;
import lombok.NonNull;
@ -120,7 +129,6 @@ import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
@ -131,9 +139,11 @@ import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.lang.reflect.Method;
import java.util.AbstractMap;
@ -157,10 +167,10 @@ import static com.plotsquared.core.util.PremiumVerification.getResourceID;
import static com.plotsquared.core.util.PremiumVerification.getUserID;
import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<Player> {
@SuppressWarnings("unused") public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform<Player> {
private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName());
private static final int BSTATS_ID = 1404;
@Getter private static WorldEdit worldEdit;
static {
try {
@ -175,12 +185,22 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
private boolean metricsStarted;
@Getter private BackupManager backupManager;
@Getter private PlatformWorldManager<World> worldManager;
private final BukkitPlayerManager playerManager = new BukkitPlayerManager();
private EconHandler econ;
private PermHandler perm;
@Getter private Injector injector;
@Inject private PlotAreaManager plotAreaManager;
@Inject private EventDispatcher eventDispatcher;
@Inject private PlotListener plotListener;
@Inject @WorldConfig private YamlConfiguration worldConfiguration;
@Inject @WorldFile private File worldfile;
@Inject private BukkitPlayerManager playerManager;
@Inject private BackupManager backupManager;
@Inject @ImpromptuPipeline private UUIDPipeline impromptuPipeline;
@Inject @BackgroundPipeline private UUIDPipeline backgroundPipeline;
@Inject private PlatformWorldManager<World> worldManager;
@Override public int[] getServerVersion() {
if (this.version == null) {
try {
@ -193,9 +213,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
} catch (NumberFormatException e) {
e.printStackTrace();
PlotSquared.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PlotSquared.debug(
StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[] {1, 13, 0};
}
}
@ -208,11 +225,14 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
@Override public void onEnable() {
this.pluginName = getDescription().getName();
// Stuff that needs to be created before the PlotSquared instance
PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer);
TaskManager.setImplementation(new BukkitTaskManager(this));
new PlotSquared(this, "Bukkit");
final PlotSquared plotSquared = new PlotSquared(this, "Bukkit");
if (PlotSquared.get().IMP.getServerVersion()[1] < 13) {
if (PlotSquared.platform().getServerVersion()[1] < 13) {
System.out.println(
"You can't use this version of PlotSquared on a server less than Minecraft 1.13.2.");
System.out
@ -222,182 +242,283 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
return;
}
// We create the injector after PlotSquared has been initialized, so that we have access
// to generated instances and settings
this.injector = Guice.createInjector(Stage.PRODUCTION, new WorldManagerModule(), new PlotSquaredModule(),
new BukkitModule(this), new BackupModule());
this.injector.injectMembers(this);
if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) {
new UpdateUtility(this).updateChecker();
injector.getInstance(UpdateUtility.class).updateChecker();
}
if (PremiumVerification.isPremium()) {
PlotSquared.log(
Captions.PREFIX + "&6PlotSquared version licensed to Spigot user " + getUserID());
PlotSquared
.log(Captions.PREFIX + "&6https://www.spigotmc.org/resources/" + getResourceID());
PlotSquared.log(Captions.PREFIX + "&6Download ID: " + getDownloadID());
PlotSquared.log(Captions.PREFIX + "&6Thanks for supporting us :)");
logger.info("[P2] PlotSquared version licensed to Spigot user {}", getUserID());
logger.info("[P2] https://www.spigotmc.org/resources/{}", getResourceID());
logger.info("[P2] Download ID: {}", getDownloadID());
logger.info("[P2] Thanks for supporting us :)");
} else {
PlotSquared.log(Captions.PREFIX + "&6Couldn't verify purchase :(");
logger.info("[P2] Couldn't verify purchase :(");
}
final UUIDPipeline impromptuPipeline = PlotSquared.get().getImpromptuUUIDPipeline();
final UUIDPipeline backgroundPipeline = PlotSquared.get().getBackgroundUUIDPipeline();
// Database
if (Settings.Enabled_Components.DATABASE) {
plotSquared.setupDatabase();
}
// Check if we need to convert old flag values, etc
if (!plotSquared.getConfigurationVersion().equalsIgnoreCase("v5")) {
// Perform upgrade
if (DBFunc.dbManager.convertFlags()) {
log(Captions.PREFIX.getTranslated() + "Flags were converted successfully!");
// Update the config version
try {
plotSquared.setConfigurationVersion("v5");
} catch (final Exception e) {
e.printStackTrace();
}
}
}
// Comments
CommentManager.registerDefaultInboxes();
plotSquared.startExpiryTasks();
// This is getting removed so I won't even bother migrating it
ChatManager.manager = this.initChatManager();
// Do stuff that was previously done in PlotSquared
// Kill entities
if (Settings.Enabled_Components.KILL_ROAD_MOBS
|| Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
this.runEntityTask();
}
// WorldEdit
if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) {
try {
logger.info("[P2] {} hooked into WorldEdit", this.getPluginName());
WorldEdit.getInstance().getEventBus().register(this.getInjector().getInstance(WESubscriber.class));
if (Settings.Enabled_Components.COMMANDS) {
new WE_Anywhere();
}
} catch (Throwable e) {
logger.error("[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master");
}
}
if (Settings.Enabled_Components.EVENTS) {
getServer().getPluginManager().registerEvents(getInjector().getInstance(PlayerEvents.class), this);
getServer().getPluginManager().registerEvents(getInjector().getInstance(EntitySpawnListener.class), this);
if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) {
getServer().getPluginManager().registerEvents(getInjector().getInstance(PaperListener.class), this);
}
this.plotListener.startRunnable();
}
// Required
getServer().getPluginManager().registerEvents(getInjector().getInstance(WorldEvents.class), this);
if (Settings.Enabled_Components.CHUNK_PROCESSOR) {
getServer().getPluginManager().registerEvents(getInjector().getInstance(ChunkListener.class), this);
}
// Start the global block queue
final GlobalBlockQueue globalBlockQueue = this.injector.getInstance(GlobalBlockQueue.class);
globalBlockQueue.runTask();
// Commands
if (Settings.Enabled_Components.COMMANDS) {
this.registerCommands();
}
// Economy
if (Settings.Enabled_Components.ECONOMY) {
TaskManager.runTask(() -> {
final PermHandler permHandler = getInjector().getInstance(PermHandler.class);
if (permHandler != null) {
permHandler.init();
}
final EconHandler econHandler = getInjector().getInstance(EconHandler.class);
if (econHandler != null) {
econHandler.init();
}
});
}
if (Settings.Enabled_Components.COMPONENT_PRESETS) {
try {
getInjector().getInstance(ComponentPresetManager.class);
} catch (final Exception e) {
logger.error("[P2] Failed to initialize the preset system", e);
}
}
// World generators:
final ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds");
final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class);
if (section != null) {
for (String world : section.getKeys(false)) {
if (world.equals("CheckingPlotSquaredGenerator")) {
continue;
}
if (worldUtil.isWorld(world)) {
this.setGenerator(world);
}
}
TaskManager.runTaskLater(() -> {
for (String world : section.getKeys(false)) {
if (world.equals("CheckingPlotSquaredGenerator")) {
continue;
}
if (!worldUtil.isWorld(world) && !world.equals("*")) {
logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly",
world, this.getPluginName());
logger.warn("[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml");
logger.warn("[P2] - Your world management plugin may be faulty (or non existent)");
logger.warn("[P2] This message may also be a false positive and could be ignored.");
this.setGenerator(world);
}
}
}, 1);
}
// Services are accessed in order
final CacheUUIDService cacheUUIDService =
new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE);
impromptuPipeline.registerService(cacheUUIDService);
backgroundPipeline.registerService(cacheUUIDService);
impromptuPipeline.registerConsumer(cacheUUIDService);
backgroundPipeline.registerConsumer(cacheUUIDService);
final CacheUUIDService cacheUUIDService = new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE);
this.impromptuPipeline.registerService(cacheUUIDService);
this.backgroundPipeline.registerService(cacheUUIDService);
this.impromptuPipeline.registerConsumer(cacheUUIDService);
this.backgroundPipeline.registerConsumer(cacheUUIDService);
// Now, if the server is in offline mode we can only use profiles and direct UUID
// access, and so we skip the player profile stuff as well as SquirrelID (Mojang lookups)
if (Settings.UUID.OFFLINE) {
final OfflineModeUUIDService offlineModeUUIDService = new OfflineModeUUIDService();
impromptuPipeline.registerService(offlineModeUUIDService);
backgroundPipeline.registerService(offlineModeUUIDService);
PlotSquared.log(Captions.PREFIX + "(UUID) Using the offline mode UUID service");
this.impromptuPipeline.registerService(offlineModeUUIDService);
this.backgroundPipeline.registerService(offlineModeUUIDService);
logger.info("[P2] (UUID) Using the offline mode UUID service");
}
final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService();
impromptuPipeline.registerService(offlinePlayerUUIDService);
backgroundPipeline.registerService(offlinePlayerUUIDService);
if (Settings.UUID.SERVICE_BUKKIT) {
final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService();
this.impromptuPipeline.registerService(offlinePlayerUUIDService);
this.backgroundPipeline.registerService(offlinePlayerUUIDService);
}
final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db");
final SQLiteUUIDService legacyUUIDService;
if (Settings.UUID.LEGACY_DATABASE_SUPPORT && MainUtil
.getFile(PlotSquared.get().IMP.getDirectory(), "usercache.db").exists()) {
.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) {
legacyUUIDService = new SQLiteUUIDService("usercache.db");
} else {
legacyUUIDService = null;
}
final LuckPermsUUIDService luckPermsUUIDService;
if (Bukkit.getPluginManager().getPlugin("LuckPerms") != null) {
if (Settings.UUID.SERVICE_LUCKPERMS &&
Bukkit.getPluginManager().getPlugin("LuckPerms") != null) {
luckPermsUUIDService = new LuckPermsUUIDService();
PlotSquared
.log(Captions.PREFIX + "(UUID) Using LuckPerms as a complementary UUID service");
logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service");
} else {
luckPermsUUIDService = null;
}
final BungeePermsUUIDService bungeePermsUUIDService;
if (Bukkit.getPluginManager().getPlugin("BungeePerms") != null) {
if (Settings.UUID.SERVICE_BUNGEE_PERMS &&
Bukkit.getPluginManager().getPlugin("BungeePerms") != null) {
bungeePermsUUIDService = new BungeePermsUUIDService();
PlotSquared
.log(Captions.PREFIX + "(UUID) Using BungeePerms as a complementary UUID service");
logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service");
} else {
bungeePermsUUIDService = null;
}
final EssentialsUUIDService essentialsUUIDService;
if (Bukkit.getPluginManager().getPlugin("Essentials") != null) {
if (Settings.UUID.SERVICE_ESSENTIALSX && Bukkit.getPluginManager().getPlugin("Essentials") != null) {
essentialsUUIDService = new EssentialsUUIDService();
PlotSquared
.log(Captions.PREFIX + "(UUID) Using Essentials as a complementary UUID service");
logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service");
} else {
essentialsUUIDService = null;
}
if (!Settings.UUID.OFFLINE) {
// If running Paper we'll also try to use their profiles
if (PaperLib.isPaper()) {
if (Bukkit.getOnlineMode() && PaperLib.isPaper() && Settings.UUID.SERVICE_PAPER) {
final PaperUUIDService paperUUIDService = new PaperUUIDService();
impromptuPipeline.registerService(paperUUIDService);
backgroundPipeline.registerService(paperUUIDService);
PlotSquared
.log(Captions.PREFIX + "(UUID) Using Paper as a complementary UUID service");
this.impromptuPipeline.registerService(paperUUIDService);
this.backgroundPipeline.registerService(paperUUIDService);
logger.info("[P2] (UUID) Using Paper as a complementary UUID service");
}
impromptuPipeline.registerService(sqLiteUUIDService);
backgroundPipeline.registerService(sqLiteUUIDService);
impromptuPipeline.registerConsumer(sqLiteUUIDService);
backgroundPipeline.registerConsumer(sqLiteUUIDService);
this.impromptuPipeline.registerService(sqLiteUUIDService);
this.backgroundPipeline.registerService(sqLiteUUIDService);
this.impromptuPipeline.registerConsumer(sqLiteUUIDService);
this.backgroundPipeline.registerConsumer(sqLiteUUIDService);
if (legacyUUIDService != null) {
impromptuPipeline.registerService(legacyUUIDService);
backgroundPipeline.registerService(legacyUUIDService);
this.impromptuPipeline.registerService(legacyUUIDService);
this.backgroundPipeline.registerService(legacyUUIDService);
}
// Plugin providers
if (luckPermsUUIDService != null) {
impromptuPipeline.registerService(luckPermsUUIDService);
backgroundPipeline.registerService(luckPermsUUIDService);
this.impromptuPipeline.registerService(luckPermsUUIDService);
this.backgroundPipeline.registerService(luckPermsUUIDService);
}
if (bungeePermsUUIDService != null) {
impromptuPipeline.registerService(bungeePermsUUIDService);
backgroundPipeline.registerService(bungeePermsUUIDService);
this.impromptuPipeline.registerService(bungeePermsUUIDService);
this.backgroundPipeline.registerService(bungeePermsUUIDService);
}
if (essentialsUUIDService != null) {
impromptuPipeline.registerService(essentialsUUIDService);
backgroundPipeline.registerService(essentialsUUIDService);
this.impromptuPipeline.registerService(essentialsUUIDService);
this.backgroundPipeline.registerService(essentialsUUIDService);
}
final SquirrelIdUUIDService impromptuMojangService =
new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT);
impromptuPipeline.registerService(impromptuMojangService);
this.impromptuPipeline.registerService(impromptuMojangService);
final SquirrelIdUUIDService backgroundMojangService =
new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT);
backgroundPipeline.registerService(backgroundMojangService);
this.backgroundPipeline.registerService(backgroundMojangService);
} else {
impromptuPipeline.registerService(sqLiteUUIDService);
backgroundPipeline.registerService(sqLiteUUIDService);
impromptuPipeline.registerConsumer(sqLiteUUIDService);
backgroundPipeline.registerConsumer(sqLiteUUIDService);
this.impromptuPipeline.registerService(sqLiteUUIDService);
this.backgroundPipeline.registerService(sqLiteUUIDService);
this.impromptuPipeline.registerConsumer(sqLiteUUIDService);
this.backgroundPipeline.registerConsumer(sqLiteUUIDService);
if (legacyUUIDService != null) {
impromptuPipeline.registerService(legacyUUIDService);
backgroundPipeline.registerService(legacyUUIDService);
this.impromptuPipeline.registerService(legacyUUIDService);
this.backgroundPipeline.registerService(legacyUUIDService);
}
}
impromptuPipeline.storeImmediately("*", DBFunc.EVERYONE);
this.impromptuPipeline.storeImmediately("*", DBFunc.EVERYONE);
if (Settings.UUID.BACKGROUND_CACHING_ENABLED) {
this.startUuidCaching(sqLiteUUIDService, cacheUUIDService);
}
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
new Placeholders().register();
injector.getInstance(Placeholders.class).register();
if (Settings.Enabled_Components.EXTERNAL_PLACEHOLDERS) {
ChatFormatter.formatters.add(new PlaceholderFormatter());
ChatFormatter.formatters.add(getInjector().getInstance(PlaceholderFormatter.class));
}
PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into PlaceholderAPI");
logger.info("[P2] PlotSquared hooked into PlaceholderAPI");
} else {
PlotSquared
.debug(Captions.PREFIX + "&6PlaceholderAPI is not in use. Hook deactivated.");
logger.info("[P2] PlaceholderAPI is not in use. Hook deactivated");
}
this.startMetrics();
if (Settings.Enabled_Components.WORLDS) {
TaskManager.IMP.taskRepeat(this::unload, 20);
TaskManager.getImplementation().taskRepeat(this::unload, 20);
try {
singleWorldListener = new SingleWorldListener(this);
singleWorldListener = getInjector().getInstance(SingleWorldListener.class);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
this.backupManager = new SimpleBackupManager();
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX + "&6Failed to initialize backup manager");
e.printStackTrace();
PlotSquared.log(Captions.PREFIX + "&6Backup features will be disabled");
this.backupManager = new NullBackupManager();
}
if (Bukkit.getPluginManager().getPlugin("Hyperverse") != null) {
this.worldManager = new HyperverseWorldManager();
} else if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) {
this.worldManager = new MultiverseWorldManager();
} else {
this.worldManager = new BukkitWorldManager();
}
PlotSquared.log(
Captions.PREFIX.getTranslated() + "Using platform world manager: " + this.worldManager
.getName());
// Clean up potential memory leak
Bukkit.getScheduler().runTaskTimer(this, () -> {
try {
@ -424,10 +545,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
event.printStackTrace();
}
}
final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
if (this.plotAreaManager instanceof SinglePlotAreaManager) {
long start = System.currentTimeMillis();
final SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea();
final SinglePlotArea area = ((SinglePlotAreaManager) this.plotAreaManager).getArea();
outer:
for (final World world : Bukkit.getWorlds()) {
@ -457,7 +578,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
final Chunk[] chunks = world.getLoadedChunks();
if (chunks.length == 0) {
if (!Bukkit.unloadWorld(world, true)) {
PlotSquared.debug("Failed to unload " + world.getName());
logger.warn("[P2] Failed to unload {}", world.getName());
}
return;
} else {
@ -491,8 +612,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
}
private void startUuidCaching(@NotNull final SQLiteUUIDService sqLiteUUIDService,
@NotNull final CacheUUIDService cacheUUIDService) {
private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService,
@Nonnull final CacheUUIDService cacheUUIDService) {
// Load all uuids into a big chunky boi queue
final Queue<UUID> uuidQueue = new LinkedBlockingQueue<>();
PlotSquared.get().forEachPlotRaw(plot -> {
@ -507,8 +628,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
}
});
PlotSquared.log(Captions.PREFIX.getTranslated() + "(UUID) " + uuidQueue.size()
+ " UUIDs will be cached.");
logger.info("[P2] (UUID) {} UUIDs will be cached", uuidQueue.size());
Executors.newSingleThreadScheduledExecutor().schedule(() -> {
// Begin by reading all the SQLite cache at once
@ -516,9 +637,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
// Now fetch names for all known UUIDs
final int totalSize = uuidQueue.size();
int read = 0;
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "(UUID) PlotSquared will fetch UUIDs in groups of "
+ Settings.UUID.BACKGROUND_LIMIT);
logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", Settings.UUID.BACKGROUND_LIMIT);
final List<UUID> uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT);
// Used to indicate that the second retrieval has been attempted
@ -526,7 +645,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
while (!uuidQueue.isEmpty() || !uuidList.isEmpty()) {
if (!uuidList.isEmpty() && secondRun) {
PlotSquared.log("Giving up on last batch. Fetching new batch instead.");
logger.warn("[P2] (UUID) Giving up on last batch. Fetching new batch instead");
uuidList.clear();
}
if (uuidList.isEmpty()) {
@ -550,15 +669,14 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
uuidList.clear();
// Print progress
final double percentage = ((double) read / (double) totalSize) * 100.0D;
PlotSquared.log(Captions.PREFIX.getTranslated() + String
.format("(UUID) PlotSquared has cached %.1f%% of UUIDs", percentage));
if (Settings.DEBUG) {
logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", String.format("%.1f%%", percentage));
}
} catch (final InterruptedException | ExecutionException e) {
PlotSquared.log("Failed to retrieve that batch. Will try again.");
e.printStackTrace();
logger.error("[P2] (UUID) Failed to retrieve last batch. Will try again", e);
}
}
PlotSquared
.log(Captions.PREFIX.getTranslated() + "(UUID) PlotSquared has cached all UUIDs");
logger.info("[P2] (UUID) PlotSquared has cached all UUIDs");
}, 10, TimeUnit.SECONDS);
}
@ -567,7 +685,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
Bukkit.getScheduler().cancelTasks(this);
}
@Override public void log(@NonNull String message) {
@Override public void log(@Nonnull String message) {
try {
message = Captions.color(message);
if (!Settings.Chat.CONSOLE_COLOR) {
@ -583,21 +701,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
this.getServer().getPluginManager().disablePlugin(this);
}
@Override public int[] getPluginVersion() {
String ver = getDescription().getVersion();
if (ver.contains("-")) {
ver = ver.split("-")[0];
}
String[] split = ver.split("\\.");
return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]),
Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return getDescription().getVersion();
}
@Override public void registerCommands() {
private void registerCommands() {
final BukkitCommand bukkitCommand = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots");
if (plotCommand != null) {
@ -615,13 +719,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
return Bukkit.getWorldContainer();
}
@Override public TaskManager getTaskManager() {
return new BukkitTaskManager(this);
}
@Override @SuppressWarnings("deprecation") public void runEntityTask() {
PlotSquared.log(Captions.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(() -> PlotSquared.get().forEachPlotArea(plotArea -> {
@SuppressWarnings("deprecation") private void runEntityTask() {
logger.info("[P2] KillAllEntities started");
TaskManager.runTaskRepeat(() -> this.plotAreaManager.forEachPlotArea(plotArea -> {
final World world = Bukkit.getWorld(plotArea.getWorldName());
try {
if (world == null) {
@ -756,7 +856,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
if (currentPlotId != null) {
entity.setMetadata("shulkerPlot",
new FixedMetadataValue(
(Plugin) PlotSquared.get().IMP, currentPlotId));
(Plugin) PlotSquared.platform(), currentPlotId));
}
}
}
@ -875,13 +975,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
@Override @Nullable
public final ChunkGenerator getDefaultWorldGenerator(@NotNull final String worldName,
public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName,
final String id) {
final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) {
result = new SingleWorldGenerator();
result = getInjector().getInstance(SingleWorldGenerator.class);
} else {
result = PlotSquared.get().IMP.getDefaultGenerator();
result = getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class));
if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) {
return null;
}
@ -889,85 +989,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
return (ChunkGenerator) result.specify(worldName);
}
@Override public void registerPlayerEvents() {
final PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this);
if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) {
getServer().getPluginManager().registerEvents(new PaperListener(), this);
}
PlotListener.startRunnable();
}
@Override public void registerForceFieldEvents() {
}
@Override public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
worldEdit = WorldEdit.getInstance();
return true;
}
return false;
}
@Override public EconHandler getEconomyHandler() {
if (econ != null) {
if (econ.init() /* is inited */) {
return econ;
} else {
return null;
}
}
try {
econ = new BukkitEconHandler();
if (econ.init()) {
return econ;
}
} catch (Throwable ignored) {
PlotSquared.debug("No economy detected!");
}
return null;
}
@Override public PermHandler getPermissionHandler() {
if (perm != null) {
if (perm.init() /* is inited */) {
return perm;
} else {
return null;
}
}
try {
perm = new BukkitPermHandler();
if (perm.init()) {
return perm;
}
} catch (Throwable ignored) {
PlotSquared.debug("No permissions detected!");
}
return null;
}
@Override public QueueProvider initBlockQueue() {
//TODO Figure out why this code is still here yet isn't being called anywhere.
// try {
// new SendChunk();
// MainUtil.canSendChunk = true;
// } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
// PlotSquared.debug(
// SendChunk.class + " does not support " + StringMan.getString(getServerVersion()));
// MainUtil.canSendChunk = false;
// }
return QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class);
}
@Override public WorldUtil initWorldUtil() {
return new BukkitUtil();
}
@Override @Nullable public GeneratorWrapper<?> getGenerator(@NonNull final String world,
@Override @Nullable public GeneratorWrapper<?> getGenerator(@Nonnull final String world,
@Nullable final String name) {
if (name == null) {
return null;
@ -978,20 +1000,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
if (gen instanceof GeneratorWrapper<?>) {
return (GeneratorWrapper<?>) gen;
}
return new BukkitPlotGenerator(world, gen);
return new BukkitPlotGenerator(world, gen, this.plotAreaManager);
} else {
return new BukkitPlotGenerator(world, PlotSquared.get().IMP.getDefaultGenerator());
return new BukkitPlotGenerator(world, getInjector()
.getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), this.plotAreaManager);
}
}
@Override public HybridUtils initHybridUtils() {
return new BukkitHybridUtils();
}
@Override public SetupUtils initSetupUtils() {
return new BukkitSetupUtils();
}
@Override public void startMetrics() {
if (this.metricsStarted) {
return;
@ -1007,7 +1022,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
map.put(plotAreaType.name().toLowerCase(), terrainTypes);
}
for (final PlotArea plotArea : PlotSquared.get().getPlotAreas()) {
for (final PlotArea plotArea : this.plotAreaManager.getAllPlotAreas()) {
final Map<String, Integer> terrainTypeMap =
map.get(plotArea.getType().name().toLowerCase());
terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(),
@ -1023,56 +1038,31 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
"WorldEdit"));
}
@Override public ChunkManager initChunkManager() {
return new BukkitChunkManager();
}
@Override public RegionManager initRegionManager() {
return new BukkitRegionManager();
}
@Override public void unregister(@NonNull final PlotPlayer player) {
@Override public void unregister(@Nonnull final PlotPlayer player) {
BukkitUtil.removePlayer(player.getUUID());
}
@Override public void registerChunkProcessor() {
getServer().getPluginManager().registerEvents(new ChunkListener(), this);
}
@Override public void registerWorldEvents() {
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@NotNull @Override public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
@Override public InventoryUtil initInventoryUtil() {
return new BukkitInventoryUtil();
}
@Override public void setGenerator(@NonNull final String worldName) {
@Override public void setGenerator(@Nonnull final String worldName) {
World world = BukkitUtil.getWorld(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig =
PlotSquared.get().worlds.getConfigurationSection("worlds." + worldName);
ConfigurationSection worldConfig = this.worldConfiguration.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", getPluginName());
PlotAreaBuilder builder = new PlotAreaBuilder().plotManager(manager)
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager)
.generatorName(worldConfig.getString("generator.init", manager))
.plotAreaType(MainUtil.getType(worldConfig))
.terrainType(MainUtil.getTerrain(worldConfig))
.settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null))
.worldName(worldName);
SetupUtils.manager.setupWorld(builder);
getInjector().getInstance(SetupUtils.class).setupWorld(builder);
world = Bukkit.getWorld(worldName);
} else {
try {
if (!PlotSquared.get().hasPlotArea(worldName)) {
if (!this.plotAreaManager.hasPlotArea(worldName)) {
SetGenCB.setGenerator(BukkitUtil.getWorld(worldName));
}
} catch (Exception e) {
PlotSquared.log("Failed to reload world: " + world + " | " + e.getMessage());
} catch (final Exception e) {
logger.error("[P2] Failed to reload world: {} | {}", world, e.getMessage());
Bukkit.getServer().unloadWorld(world, false);
return;
}
@ -1082,16 +1072,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
if (gen instanceof BukkitPlotGenerator) {
PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
} else if (gen != null) {
PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen));
} else if (PlotSquared.get().worlds.contains("worlds." + worldName)) {
PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen, this.plotAreaManager));
} else if (this.worldConfiguration.contains("worlds." + worldName)) {
PlotSquared.get().loadWorld(worldName, null);
}
}
@Override public SchematicHandler initSchematicHandler() {
return new BukkitSchematicHandler();
}
/**
* Attempt to retrieve a {@link PlotPlayer} from a player identifier.
* This method accepts:
@ -1115,11 +1101,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
return BukkitUtil.getPlayer((OfflinePlayer) player);
}
if (player instanceof String) {
return (PlotPlayer<Player>) PlotSquared.imp().getPlayerManager()
return (PlotPlayer<Player>) PlotSquared.platform().getPlayerManager()
.getPlayerIfExists((String) player);
}
if (player instanceof UUID) {
return (PlotPlayer<Player>) PlotSquared.imp().getPlayerManager()
return (PlotPlayer<Player>) PlotSquared.platform().getPlayerManager()
.getPlayerIfExists((UUID) player);
}
return null;
@ -1131,8 +1117,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
}
@Override public GeneratorWrapper<?> wrapPlotGenerator(@Nullable final String world,
@NonNull final IndependentPlotGenerator generator) {
return new BukkitPlotGenerator(world, generator);
@Nonnull final IndependentPlotGenerator generator) {
return new BukkitPlotGenerator(world, generator, this.plotAreaManager);
}
@Override public List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds() {
@ -1145,16 +1131,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain<
return names;
}
@Override public Actor getConsole() {
@NotNull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
WorldEditPlugin wePlugin =
((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
return wePlugin.wrapCommandSender(console);
}
@Override @NotNull
public PlayerManager<? extends PlotPlayer<Player>, ? extends Player> getPlayerManager() {
return this.playerManager;
@Override public com.plotsquared.core.location.World<?> getPlatformWorld(@Nonnull final String worldName) {
return BukkitWorld.of(worldName);
}
@Override @NotNull public Audience getConsoleAudience() {

View File

@ -26,11 +26,12 @@
package com.plotsquared.bukkit.entity;
import lombok.Getter;
import lombok.NonNull;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import javax.annotation.Nonnull;
@Getter
public abstract class EntityWrapper {
@ -43,7 +44,7 @@ public abstract class EntityWrapper {
public double y;
public double z;
EntityWrapper(@NonNull final Entity entity) {
EntityWrapper(@Nonnull final Entity entity) {
this.entity = entity;
this.type = entity.getType();

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.bukkit.entity;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import org.bukkit.Art;
import org.bukkit.DyeColor;
import org.bukkit.Location;
@ -55,11 +55,15 @@ import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public final class ReplicatingEntityWrapper extends EntityWrapper {
private static final Logger logger = LoggerFactory.getLogger("P2/" + ReplicatingEntityWrapper.class.getSimpleName());
private final short depth;
private final int hash;
private final EntityBaseStats base = new EntityBaseStats();
@ -331,10 +335,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
this.dataByte = (byte) 0;
}
storeLiving((LivingEntity) entity);
return;
// END LIVING //
default:
PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
}
}
@ -390,7 +391,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
try {
entity.getInventory().setContents(this.inventory);
} catch (IllegalArgumentException e) {
PlotSquared.debug("&c[WARN] Failed to restore inventory.\n Reason: " + e.getMessage());
logger.error("[P2] Failed to restore inventory", e);
}
}
@ -736,7 +737,9 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
restoreLiving((LivingEntity) entity);
return entity;
default:
PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
if (Settings.DEBUG) {
logger.info("[P2] Could not identify entity: {}", entity.getType());
}
return entity;
// END LIVING
}

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.bukkit.entity;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.BukkitPlatform;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
@ -53,7 +53,7 @@ public class TeleportEntityWrapper extends EntityWrapper {
getEntity().setInvulnerable(invulnerableOld);
getEntity().setFireTicks(fireTicksOld);
getEntity().setTicksLived(livingTicksOld);
getEntity().removeMetadata("ps-tmp-teleport", BukkitMain.getPlugin(BukkitMain.class));
getEntity().removeMetadata("ps-tmp-teleport", BukkitPlatform.getPlugin(BukkitPlatform.class));
}
return getEntity();
}
@ -78,7 +78,7 @@ public class TeleportEntityWrapper extends EntityWrapper {
this.fireTicksOld = this.getEntity().getFireTicks();
this.livingTicksOld = this.getEntity().getTicksLived();
this.getEntity().setMetadata("ps-tmp-teleport",
new FixedMetadataValue(BukkitMain.getPlugin(BukkitMain.class), oldLocation));
new FixedMetadataValue(BukkitPlatform.getPlugin(BukkitPlatform.class), oldLocation));
final Chunk newChunk = getNewChunk();
this.getEntity().teleport(
new Location(newChunk.getWorld(), newChunk.getX() << 4, 5000, newChunk.getZ() << 4));

View File

@ -29,32 +29,40 @@ import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.location.ChunkWrapper;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Random;
final class BlockStatePopulator extends BlockPopulator {
private final IndependentPlotGenerator plotGenerator;
private final PlotAreaManager plotAreaManager;
private LocalBlockQueue queue;
public BlockStatePopulator(IndependentPlotGenerator plotGenerator) {
public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator,
@Nonnull final PlotAreaManager plotAreaManager) {
this.plotGenerator = plotGenerator;
this.plotAreaManager = plotAreaManager;
}
@Override
public void populate(@NotNull final World world, @NotNull final Random random,
@NotNull final Chunk source) {
public void populate(@Nonnull final World world, @Nonnull final Random random,
@Nonnull final Chunk source) {
if (this.queue == null) {
this.queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
this.queue = PlotSquared.platform().getGlobalBlockQueue()
.getNewQueue(world.getName(), false);
}
final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null);
if (area == null) {
return;
}
final PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
final ChunkWrapper wrap =
new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ());
final ScopedLocalBlockQueue chunk = this.queue.getForChunk(wrap.x, wrap.z);

View File

@ -29,7 +29,7 @@ import com.plotsquared.core.generator.AugmentedUtils;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Random;
@ -51,7 +51,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator {
}
@Override
public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk source) {
public void populate(@Nonnull World world, @Nonnull Random random, @Nonnull Chunk source) {
AugmentedUtils.generate(source, world.getName(), source.getX(), source.getZ(), null);
}
}

View File

@ -33,6 +33,7 @@ import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.generator.SingleWorldGenerator;
import com.plotsquared.core.location.ChunkWrapper;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.MainUtil;
@ -42,7 +43,7 @@ import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
@ -54,6 +55,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
@SuppressWarnings("unused") public final boolean PAPER_ASYNC_SAFE = true;
private final PlotAreaManager plotAreaManager;
private final IndependentPlotGenerator plotGenerator;
private final ChunkGenerator platformGenerator;
private final boolean full;
@ -62,24 +64,25 @@ public class BukkitPlotGenerator extends ChunkGenerator
@Getter private final String levelName;
public BukkitPlotGenerator(String name, IndependentPlotGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Generator may not be null!");
}
public BukkitPlotGenerator(@Nonnull final String name,
@Nonnull final IndependentPlotGenerator generator,
@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
this.levelName = name;
this.plotGenerator = generator;
this.platformGenerator = this;
this.populators = new ArrayList<>();
this.populators.add(new BlockStatePopulator(this.plotGenerator));
this.populators.add(new BlockStatePopulator(this.plotGenerator, this.plotAreaManager));
this.full = true;
MainUtil.initCache();
}
public BukkitPlotGenerator(final String world, final ChunkGenerator cg) {
public BukkitPlotGenerator(final String world, final ChunkGenerator cg, @Nonnull final PlotAreaManager plotAreaManager) {
if (cg instanceof BukkitPlotGenerator) {
throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName()
+ " is already a BukkitPlotGenerator!");
}
this.plotAreaManager = plotAreaManager;
this.levelName = world;
this.full = false;
this.platformGenerator = cg;
@ -103,12 +106,12 @@ public class BukkitPlotGenerator extends ChunkGenerator
return this.platformGenerator;
}
@Override @NotNull public List<BlockPopulator> getDefaultPopulators(@NotNull World world) {
@Override @Nonnull public List<BlockPopulator> getDefaultPopulators(@Nonnull World world) {
try {
if (!this.loaded) {
String name = world.getName();
PlotSquared.get().loadWorld(name, this);
Set<PlotArea> areas = PlotSquared.get().getPlotAreas(name);
final Set<PlotArea> areas = this.plotAreaManager.getPlotAreasSet(name);
if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next();
if (!area.isMobSpawning()) {
@ -147,9 +150,9 @@ public class BukkitPlotGenerator extends ChunkGenerator
return toAdd;
}
@Override @NotNull
public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z,
@NotNull BiomeGrid biome) {
@Override @Nonnull
public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z,
@Nonnull BiomeGrid biome) {
GenChunk result = new GenChunk();
if (this.getPlotGenerator() instanceof SingleWorldGenerator) {
@ -198,8 +201,8 @@ public class BukkitPlotGenerator extends ChunkGenerator
if (ChunkManager.preProcessChunk(loc, result)) {
return;
}
PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
if (area == null && (area = PlotSquared.get().getPlotArea(this.levelName, null)) == null) {
PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null);
if (area == null && (area = this.plotAreaManager.getPlotArea(this.levelName, null)) == null) {
throw new IllegalStateException(
"Cannot regenerate chunk that does not belong to a plot area." + " Location: " + loc
+ ", world: " + world);
@ -213,7 +216,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
ChunkManager.postProcessChunk(loc, result);
}
@Override public boolean canSpawn(@NotNull final World world, final int x, final int z) {
@Override public boolean canSpawn(@Nonnull final World world, final int x, final int z) {
return true;
}

View File

@ -38,7 +38,7 @@ import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import org.jetbrains.annotations.Range;
import java.util.Random;
@ -61,7 +61,7 @@ final class DelegatePlotGenerator extends IndependentPlotGenerator {
}
@Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max);
return PlotSquared.platform().getDefaultGenerator().getNewPlotArea(world, id, min, max);
}
@Override public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) {
@ -74,21 +74,21 @@ final class DelegatePlotGenerator extends IndependentPlotGenerator {
ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() {
@Override
public void setBiome(@Range(from = 0, to = 15) int x,
@Range(from = 0, to = 15) int z, @NotNull Biome biome) {
@Range(from = 0, to = 15) int z, @Nonnull Biome biome) {
result.setBiome(x, z, BukkitAdapter.adapt(biome));
}
//do not annotate with Override until we discontinue support for 1.4.4
public void setBiome(int x, int y, int z, @NotNull Biome biome) {
public void setBiome(int x, int y, int z, @Nonnull Biome biome) {
result.setBiome(x, z, BukkitAdapter.adapt(biome));
}
@Override @NotNull public Biome getBiome(int x, int z) {
@Override @Nonnull public Biome getBiome(int x, int z) {
return Biome.FOREST;
}
@Override public @NotNull Biome getBiome(int x, int y, int z) {
@Override public @Nonnull Biome getBiome(int x, int y, int z) {
return Biome.FOREST;
}
};

View File

@ -0,0 +1,55 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.backup.BackupProfile;
import com.plotsquared.core.backup.NullBackupManager;
import com.plotsquared.core.backup.PlayerBackupProfile;
import com.plotsquared.core.backup.SimpleBackupManager;
import com.plotsquared.core.inject.factory.PlayerBackupProfileFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BackupModule extends AbstractModule {
private static final Logger logger = LoggerFactory.getLogger("P2/" + BackupModule.class.getSimpleName());
@Override protected void configure() {
try {
install(new FactoryModuleBuilder()
.implement(BackupProfile.class, PlayerBackupProfile.class).build(PlayerBackupProfileFactory.class));
bind(BackupManager.class).to(SimpleBackupManager.class);
} catch (final Exception e) {
logger.error("[P2] Failed to initialize backup manager", e);
logger.error("[P2] Backup features will be disabled");
bind(BackupManager.class).to(NullBackupManager.class);
}
}
}

View File

@ -0,0 +1,122 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.util.Providers;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.bukkit.player.BukkitPlayerManager;
import com.plotsquared.bukkit.queue.BukkitLocalQueue;
import com.plotsquared.bukkit.schematic.BukkitSchematicHandler;
import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitEconHandler;
import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitPermHandler;
import com.plotsquared.bukkit.util.BukkitRegionManager;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotPlatform;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.generator.HybridGen;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.inject.annotations.ConsoleActor;
import com.plotsquared.core.inject.annotations.DefaultGenerator;
import com.plotsquared.core.inject.factory.HybridPlotWorldFactory;
import com.plotsquared.core.plot.world.DefaultPlotAreaManager;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.QueueProvider;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.InventoryUtil;
import com.plotsquared.core.util.PermHandler;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.extension.platform.Actor;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import javax.annotation.Nonnull;
@RequiredArgsConstructor public class BukkitModule extends AbstractModule {
private final BukkitPlatform bukkitPlatform;
@Override protected void configure() {
bind(PlayerManager.class).to(BukkitPlayerManager.class);
bind(JavaPlugin.class).toInstance(bukkitPlatform);
bind(PlotPlatform.class).toInstance(bukkitPlatform);
bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class);
// Console actor
@Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit"));
bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console));
bind(InventoryUtil.class).to(BukkitInventoryUtil.class);
bind(SetupUtils.class).to(BukkitSetupUtils.class);
bind(WorldUtil.class).to(BukkitUtil.class);
bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue(
QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class), 1, Settings.QUEUE.TARGET_TIME));
bind(ChunkManager.class).to(BukkitChunkManager.class);
bind(RegionManager.class).to(BukkitRegionManager.class);
bind(SchematicHandler.class).to(BukkitSchematicHandler.class);
this.setupVault();
if (Settings.Enabled_Components.WORLDS) {
bind(PlotAreaManager.class).to(SinglePlotAreaManager.class);
} else {
bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class);
}
install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class));
}
private void setupVault() {
if (Bukkit.getPluginManager().isPluginEnabled("Vault")) {
BukkitPermHandler bukkitPermHandler = null;
try {
bukkitPermHandler = new BukkitPermHandler();
bind(PermHandler.class).toInstance(bukkitPermHandler);
} catch (final Exception ignored) {
bind(PermHandler.class).toProvider(Providers.of(null));
}
try {
final BukkitEconHandler bukkitEconHandler = new BukkitEconHandler(bukkitPermHandler);
bind(EconHandler.class).toInstance(bukkitEconHandler);
} catch (final Exception ignored) {
bind(EconHandler.class).toProvider(Providers.of(null));
}
} else {
bind(PermHandler.class).toProvider(Providers.of(null));
bind(EconHandler.class).toProvider(Providers.of(null));
}
}
}

View File

@ -0,0 +1,52 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.inject;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.managers.BukkitWorldManager;
import com.plotsquared.bukkit.managers.HyperverseWorldManager;
import com.plotsquared.bukkit.managers.MultiverseWorldManager;
import com.plotsquared.core.util.PlatformWorldManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
public class WorldManagerModule extends AbstractModule {
@Provides
@Singleton
PlatformWorldManager<World> provideWorldManager() {
if (Bukkit.getPluginManager().getPlugin("Hyperverse") != null) {
return new HyperverseWorldManager();
} else if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) {
return new MultiverseWorldManager();
} else {
return new BukkitWorldManager();
}
}
}

View File

@ -25,10 +25,12 @@
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.ReflectionUtils.RefClass;
import com.plotsquared.core.util.ReflectionUtils.RefField;
import com.plotsquared.core.util.ReflectionUtils.RefMethod;
@ -51,6 +53,9 @@ import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.HashSet;
@ -60,12 +65,17 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass;
@SuppressWarnings("unused")
public class ChunkListener implements Listener {
private static final Logger logger = LoggerFactory.getLogger("P2/" + ChunkListener.class.getSimpleName());
private final PlotAreaManager plotAreaManager;
private RefMethod methodGetHandleChunk;
private RefField mustSave;
private Chunk lastChunk;
private boolean ignoreUnload = false;
public ChunkListener() {
@Inject public ChunkListener(@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
if (Settings.Chunk_Processor.AUTO_TRIM) {
try {
RefClass classChunk = getRefClass("{nms}.Chunk");
@ -73,9 +83,6 @@ public class ChunkListener implements Listener {
this.mustSave = classChunk.getField("mustSave");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
} catch (Throwable ignored) {
PlotSquared.debug(PlotSquared.get().IMP.getPluginName()
+ "/Server not compatible for chunk processor trim/gc");
Settings.Chunk_Processor.AUTO_TRIM = false;
}
}
@ -90,7 +97,7 @@ public class ChunkListener implements Listener {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
if (!this.plotAreaManager.hasPlotArea(worldName)) {
continue;
}
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
@ -150,23 +157,23 @@ public class ChunkListener implements Listener {
int z = chunkZ << 4;
int x2 = x + 15;
int z2 = z + 15;
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
Plot plot = Location.at(world, x, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x2, 1, z2).getOwnedPlotAbs();
plot = Location.at(world, x2, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x2, 1, z).getOwnedPlotAbs();
plot = Location.at(world, x2, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x, 1, z2).getOwnedPlotAbs();
plot = Location.at(world, x, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs();
plot = Location.at(world, x + 7, 1, z + 7).getOwnedPlotAbs();
return plot != null && plot.hasOwner();
}
@ -177,7 +184,7 @@ public class ChunkListener implements Listener {
Chunk chunk = event.getChunk();
if (Settings.Chunk_Processor.AUTO_TRIM) {
String world = chunk.getWorld().getName();
if (PlotSquared.get().hasPlotArea(world)) {
if (this.plotAreaManager.hasPlotArea(world)) {
if (unloadChunk(world, chunk, true)) {
return;
}
@ -200,7 +207,7 @@ public class ChunkListener implements Listener {
event.setCancelled(true);
return;
}
if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) {
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
@ -230,7 +237,7 @@ public class ChunkListener implements Listener {
event.setCancelled(true);
return;
}
if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) {
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
@ -251,7 +258,6 @@ public class ChunkListener implements Listener {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug("Successfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
@ -259,7 +265,6 @@ public class ChunkListener implements Listener {
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug("Successfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
@ -269,7 +274,6 @@ public class ChunkListener implements Listener {
if (i >= tiles.length - Settings.Chunk_Processor.MAX_TILES) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug("Successfully processed and unloaded chunk!");
chunk.unload(true);
return;
}
@ -281,7 +285,7 @@ public class ChunkListener implements Listener {
}
public boolean processChunk(Chunk chunk, boolean unload) {
if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) {
if (!this.plotAreaManager.hasPlotArea(chunk.getWorld().getName())) {
return false;
}
Entity[] entities = chunk.getEntities();
@ -296,16 +300,9 @@ public class ChunkListener implements Listener {
toRemove--;
}
}
PlotSquared.debug(
"PlotSquared detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (
chunk.getX() << 4));
}
if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) {
PlotSquared.debug(
"PlotSquared detected unsafe chunk: " + (chunk.getX() << 4) + "," + (
chunk.getX() << 4));
cleanChunk(chunk);
return true;
}

View File

@ -53,7 +53,7 @@ import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.List;
@ -65,7 +65,7 @@ public class EntitySpawnListener implements Listener {
private static String areaName = null;
public static void testNether(final Entity entity) {
@NotNull World world = entity.getWorld();
@Nonnull World world = entity.getWorld();
if (world.getEnvironment() != World.Environment.NETHER
&& world.getEnvironment() != World.Environment.THE_END) {
return;
@ -74,11 +74,11 @@ public class EntitySpawnListener implements Listener {
}
public static void testCreate(final Entity entity) {
@NotNull World world = entity.getWorld();
@Nonnull World world = entity.getWorld();
if (areaName == world.getName()) {
} else {
areaName = world.getName();
hasPlotArea = PlotSquared.get().hasPlotArea(areaName);
hasPlotArea = PlotSquared.get().getPlotAreaManager().hasPlotArea(areaName);
}
if (!hasPlotArea) {
return;
@ -87,12 +87,12 @@ public class EntitySpawnListener implements Listener {
}
public static void test(Entity entity) {
@NotNull World world = entity.getWorld();
@Nonnull World world = entity.getWorld();
List<MetadataValue> meta = entity.getMetadata(KEY);
if (meta.isEmpty()) {
if (PlotSquared.get().hasPlotArea(world.getName())) {
if (PlotSquared.get().getPlotAreaManager().hasPlotArea(world.getName())) {
entity.setMetadata(KEY,
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, entity.getLocation()));
new FixedMetadataValue((Plugin) PlotSquared.platform(), entity.getLocation()));
}
} else {
org.bukkit.Location origin = (org.bukkit.Location) meta.get(0).value();
@ -161,13 +161,13 @@ public class EntitySpawnListener implements Listener {
case SHULKER:
if (!entity.hasMetadata("shulkerPlot")) {
entity.setMetadata("shulkerPlot",
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot.getId()));
new FixedMetadataValue((Plugin) PlotSquared.platform(), plot.getId()));
}
}
}
@EventHandler public void onChunkLoad(ChunkLoadEvent event) {
@NotNull Chunk chunk = event.getChunk();
@Nonnull Chunk chunk = event.getChunk();
for (final Entity entity : chunk.getEntities()) {
testCreate(entity);
}

View File

@ -32,8 +32,8 @@ import com.destroystokyo.paper.event.entity.PreSpawnerSpawnEvent;
import com.destroystokyo.paper.event.entity.SlimePathfindEvent;
import com.destroystokyo.paper.event.player.PlayerLaunchProjectileEvent;
import com.destroystokyo.paper.event.server.AsyncTabCompleteEvent;
import com.google.inject.Inject;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.command.Command;
import com.plotsquared.core.command.MainCommand;
import com.plotsquared.core.configuration.Captions;
@ -43,6 +43,7 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import org.bukkit.Chunk;
import org.bukkit.block.Block;
import org.bukkit.block.TileState;
@ -58,6 +59,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.projectiles.ProjectileSource;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
@ -71,8 +73,13 @@ import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class PaperListener implements Listener {
private final PlotAreaManager plotAreaManager;
private Chunk lastChunk;
@Inject public PaperListener(@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@EventHandler public void onEntityPathfind(EntityPathfindEvent event) {
if (!Settings.Paper_Components.ENTITY_PATHING) {
return;
@ -305,7 +312,7 @@ public class PaperListener implements Listener {
return;
}
Location location = BukkitUtil.getLocation(entity);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
PlotPlayer<?> pp = BukkitUtil.getPlayer((Player) shooter);

View File

@ -27,6 +27,7 @@ package com.plotsquared.bukkit.listener;
import com.destroystokyo.paper.MaterialTags;
import com.google.common.base.Charsets;
import com.google.inject.Inject;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.UpdateUtility;
@ -99,14 +100,18 @@ import com.plotsquared.core.plot.flag.implementations.VillagerInteractFlag;
import com.plotsquared.core.plot.flag.implementations.VineGrowFlag;
import com.plotsquared.core.plot.flag.types.BlockTypeWrapper;
import com.plotsquared.core.plot.message.PlotMessage;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EntityUtil;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.PremiumVerification;
import com.plotsquared.core.util.RegExUtil;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.entity.EntityCategories;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.world.block.BlockType;
import io.papermc.lib.PaperLib;
@ -210,6 +215,7 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.ArrayList;
@ -224,12 +230,16 @@ import java.util.regex.Pattern;
/**
* Player Events involving plots.
*/
@SuppressWarnings("unused")
public class PlayerEvents extends PlotListener implements Listener {
@SuppressWarnings("unused") public class PlayerEvents extends PlotListener implements Listener {
public static final com.sk89q.worldedit.world.entity.EntityType FAKE_ENTITY_TYPE =
new com.sk89q.worldedit.world.entity.EntityType("plotsquared:fake");
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final WorldEdit worldEdit;
private boolean pistonBlocks = true;
private float lastRadius;
// To prevent recursion
private boolean tmpTeleport = true;
@ -237,7 +247,14 @@ public class PlayerEvents extends PlotListener implements Listener {
private PlayerMoveEvent moveTmp;
private String internalVersion;
{
@Inject public PlayerEvents(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final WorldEdit worldEdit,
@Nonnull final WorldUtil worldUtil) {
super(eventDispatcher);
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.worldEdit = worldEdit;
try {
fieldPlayer = PlayerEvent.class.getDeclaredField("player");
fieldPlayer.setAccessible(true);
@ -253,9 +270,10 @@ public class PlayerEvents extends PlotListener implements Listener {
int z = bloc.getBlockZ();
int distance = Bukkit.getViewDistance() * 16;
for (final PlotPlayer<?> player : PlotSquared.imp().getPlayerManager().getPlayers()) {
for (final PlotPlayer<?> player : PlotSquared.platform().getPlayerManager()
.getPlayers()) {
Location location = player.getLocation();
if (location.getWorld().equals(world)) {
if (location.getWorldName().equals(world)) {
if (16 * Math.abs(location.getX() - x) / 16 > distance
|| 16 * Math.abs(location.getZ() - z) / 16 > distance) {
continue;
@ -358,20 +376,21 @@ public class PlayerEvents extends PlotListener implements Listener {
if (plot.isMerged()) {
disable = true;
for (UUID owner : plot.getOwners()) {
if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(owner) != null) {
if (PlotSquared.platform().getPlayerManager().getPlayerIfExists(owner)
!= null) {
disable = false;
break;
}
}
} else {
disable =
PlotSquared.imp().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs())
== null;
disable = PlotSquared.platform().getPlayerManager()
.getPlayerIfExists(plot.getOwnerAbs()) == null;
}
}
if (disable) {
for (UUID trusted : plot.getTrusted()) {
if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(trusted) != null) {
if (PlotSquared.platform().getPlayerManager().getPlayerIfExists(trusted)
!= null) {
disable = false;
break;
}
@ -385,7 +404,8 @@ public class PlayerEvents extends PlotListener implements Listener {
}
}
if (Settings.Redstone.DISABLE_UNOCCUPIED) {
for (final PlotPlayer<?> player : PlotSquared.imp().getPlayerManager().getPlayers()) {
for (final PlotPlayer<?> player : PlotSquared.platform().getPlayerManager()
.getPlayers()) {
if (plot.equals(player.getCurrentPlot())) {
return;
}
@ -455,16 +475,16 @@ public class PlayerEvents extends PlotListener implements Listener {
}
switch (piston.getFacing()) {
case EAST:
location.setX(location.getX() + 1);
location = location.add(1, 0, 0);
break;
case SOUTH:
location.setX(location.getX() - 1);
location = location.add(-1, 0, 0);
break;
case WEST:
location.setZ(location.getZ() + 1);
location = location.add(0, 0, 1);
break;
case NORTH:
location.setZ(location.getZ() - 1);
location = location.add(0, 0, -1);
break;
}
Plot newPlot = area.getOwnedPlotAbs(location);
@ -490,7 +510,7 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}
Location location = BukkitUtil.getLocation(entity);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
PlotPlayer<Player> pp = BukkitUtil.getPlayer((Player) shooter);
@ -504,7 +524,7 @@ public class PlayerEvents extends PlotListener implements Listener {
@EventHandler public boolean onProjectileHit(ProjectileHitEvent event) {
Projectile entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return true;
}
PlotArea area = location.getPlotArea();
@ -680,7 +700,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (!player.hasPlayedBefore() && player.isOnline()) {
player.saveData();
}
PlotSquared.get().getEventDispatcher().doJoinTask(pp);
this.eventDispatcher.doJoinTask(pp);
}, 20);
if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated())
@ -703,7 +723,7 @@ public class PlayerEvents extends PlotListener implements Listener {
public void playerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
PlotPlayer<Player> pp = BukkitUtil.getPlayer(player);
PlotSquared.get().getEventDispatcher().doRespawnTask(pp);
this.eventDispatcher.doRespawnTask(pp);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -803,7 +823,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
} else if (toPlot != null) {
vehicle.setMetadata("plot",
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, toPlot));
new FixedMetadataValue((Plugin) PlotSquared.platform(), toPlot));
}
}
}
@ -973,7 +993,7 @@ public class PlayerEvents extends PlotListener implements Listener {
Set<Player> recipients = event.getRecipients();
recipients.clear();
Set<Player> spies = new HashSet<>();
for (final PlotPlayer<?> pp : PlotSquared.imp().getPlayerManager().getPlayers()) {
for (final PlotPlayer<?> pp : PlotSquared.platform().getPlayerManager().getPlayers()) {
if (pp.getAttribute("chatspy")) {
spies.add(((BukkitPlayer) pp).player);
} else {
@ -1000,7 +1020,8 @@ public class PlayerEvents extends PlotListener implements Listener {
player.sendMessage(spyMessage);
}
}
PlotSquared.debug(full);
// TODO: Re-implement
// PlotSquared.debug(full);
}
@EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) {
@ -1065,9 +1086,9 @@ public class PlayerEvents extends PlotListener implements Listener {
if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) {
return;
}
if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) {
if (this.worldEdit!= null && pp.getAttribute("worldedit")) {
if (player.getInventory().getItemInMainHand().getType() == Material
.getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) {
.getMaterial(this.worldEdit.getConfiguration().wandItem)) {
return;
}
}
@ -1082,7 +1103,7 @@ public class PlayerEvents extends PlotListener implements Listener {
PlotArea area = location.getPlotArea();
boolean plotArea = location.isPlotArea();
if (!plotArea) {
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
return;
@ -1105,7 +1126,7 @@ public class PlayerEvents extends PlotListener implements Listener {
.equals(EntityType.MINECART_TNT)) {
if (!near.hasMetadata("plot")) {
near.setMetadata("plot",
new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot));
new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
}
@ -1138,7 +1159,7 @@ public class PlayerEvents extends PlotListener implements Listener {
if (plot != null) {
plotExit(pp, plot);
}
if (PlotSquared.get().worldedit != null) {
if (this.worldEdit != null) {
if (!Permissions.hasPermission(pp, Captions.PERMISSION_WORLDEDIT_BYPASS)) {
if (pp.getAttribute("worldedit")) {
pp.removeAttribute("worldedit");
@ -1178,7 +1199,7 @@ public class PlayerEvents extends PlotListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityBlockForm(EntityBlockFormEvent event) {
String world = event.getBlock().getWorld().getName();
if (!PlotSquared.get().hasPlotArea(world)) {
if (!this.plotAreaManager.hasPlotArea(world)) {
return;
}
Location location = BukkitUtil.getLocation(event.getBlock().getLocation());
@ -1509,13 +1530,14 @@ public class PlayerEvents extends PlotListener implements Listener {
Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ());
PlotArea area = location.getPlotArea();
if (area == null) {
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
for (Block block1 : event.getBlocks()) {
Location bloc = BukkitUtil.getLocation(block1.getLocation());
if (bloc.isPlotArea() || bloc.add(relative.getBlockX(),
relative.getBlockY(), relative.getBlockZ()).isPlotArea()) {
if (bloc.isPlotArea() || bloc
.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())
.isPlotArea()) {
event.setCancelled(true);
return;
}
@ -1546,8 +1568,8 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}
}
if (!plot.equals(area.getOwnedPlot(location.add(
relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) {
if (!plot.equals(area.getOwnedPlot(
location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) {
// This branch is only necessary to prevent pistons from extending
// if they are: on a plot edge, facing outside the plot, and not
// pushing any blocks
@ -1563,13 +1585,14 @@ public class PlayerEvents extends PlotListener implements Listener {
Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ());
PlotArea area = location.getPlotArea();
if (area == null) {
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
for (Block block1 : event.getBlocks()) {
Location bloc = BukkitUtil.getLocation(block1.getLocation());
if (bloc.isPlotArea() || bloc.add(relative.getBlockX(),
relative.getBlockY(), relative.getBlockZ()).isPlotArea()) {
if (bloc.isPlotArea() || bloc
.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())
.isPlotArea()) {
event.setCancelled(true);
return;
}
@ -1647,7 +1670,7 @@ public class PlayerEvents extends PlotListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent event) {
if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) {
if (!this.plotAreaManager.hasPlotArea(event.getWorld().getName())) {
return;
}
List<org.bukkit.block.BlockState> blocks = event.getBlocks();
@ -1710,7 +1733,7 @@ public class PlayerEvents extends PlotListener implements Listener {
return;
}*/
HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !PlotSquared.get()
if (!(entity instanceof Player) || !this.plotAreaManager
.hasPlotArea(entity.getWorld().getName())) {
return;
}
@ -1852,7 +1875,7 @@ public class PlayerEvents extends PlotListener implements Listener {
public void onPotionSplash(LingeringPotionSplashEvent event) {
Projectile entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
if (!this.onProjectileHit(event)) {
@ -1918,8 +1941,8 @@ public class PlayerEvents extends PlotListener implements Listener {
public void onBigBoom(BlockExplodeEvent event) {
Block block = event.getBlock();
Location location = BukkitUtil.getLocation(block.getLocation());
String world = location.getWorld();
if (!PlotSquared.get().hasPlotArea(world)) {
String world = location.getWorldName();
if (!this.plotAreaManager.hasPlotArea(world)) {
return;
}
PlotArea area = location.getPlotArea();
@ -1955,7 +1978,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
if (event.getAction() == Action.RIGHT_CLICK_AIR) {
Material item = event.getMaterial();
if (item.toString().toLowerCase().endsWith("egg")) {
if (item.toString().toLowerCase().endsWith("_egg")) {
event.setCancelled(true);
event.setUseItemInHand(Event.Result.DENY);
}
@ -1967,11 +1990,11 @@ public class PlayerEvents extends PlotListener implements Listener {
if (type == Material.AIR) {
type = offType;
}
if (type.toString().toLowerCase().endsWith("egg")) {
if (type.toString().toLowerCase().endsWith("_egg")) {
Block block = player.getTargetBlockExact(5, FluidCollisionMode.SOURCE_ONLY);
if (block != null && block.getType() != Material.AIR) {
Location location = BukkitUtil.getLocation(block.getLocation());
if (!PlotSquared.get().getEventDispatcher()
if (!this.eventDispatcher
.checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null,
true)) {
event.setCancelled(true);
@ -2102,13 +2125,13 @@ public class PlayerEvents extends PlotListener implements Listener {
default:
return;
}
if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) {
if (this.worldEdit != null && pp.getAttribute("worldedit")) {
if (event.getMaterial() == Material
.getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) {
.getMaterial(this.worldEdit.getConfiguration().wandItem)) {
return;
}
}
if (!PlotSquared.get().getEventDispatcher()
if (!this.eventDispatcher
.checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) {
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
@ -2193,7 +2216,7 @@ public class PlayerEvents extends PlotListener implements Listener {
Block block = event.getBlock();
World world = block.getWorld();
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
if (!this.plotAreaManager.hasPlotArea(worldName)) {
return;
}
Location location = BukkitUtil.getLocation(block.getLocation());
@ -2220,7 +2243,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
} else if (event.getTo() == Material.AIR) {
event.getEntity()
.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot));
.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
@ -2396,7 +2419,7 @@ public class PlayerEvents extends PlotListener implements Listener {
TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName());
BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer());
pp.unregister();
PlotListener.logout(pp.getUUID());
this.logout(pp.getUUID());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -2463,7 +2486,7 @@ public class PlayerEvents extends PlotListener implements Listener {
}
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
entity
.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot));
.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot));
}
}
@ -2477,7 +2500,6 @@ public class PlayerEvents extends PlotListener implements Listener {
}
Player p = event.getPlayer();
if (p == null) {
PlotSquared.debug("PlotSquared does not support HangingPlaceEvent for non-players.");
event.setCancelled(true);
return;
}
@ -2718,7 +2740,7 @@ public class PlayerEvents extends PlotListener implements Listener {
public void onPotionSplash(PotionSplashEvent event) {
ThrownPotion damager = event.getPotion();
Location location = BukkitUtil.getLocation(damager);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
int count = 0;
@ -2748,7 +2770,7 @@ public class PlayerEvents extends PlotListener implements Listener {
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
Location location = BukkitUtil.getLocation(damager);
if (!PlotSquared.get().hasPlotArea(location.getWorld())) {
if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) {
return;
}
Entity victim = event.getEntity();

View File

@ -37,7 +37,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@ -50,7 +50,7 @@ public class SingleWorldListener implements Listener {
private Method methodGetHandleChunk;
private Field mustSave;
public SingleWorldListener(Plugin plugin) throws Exception {
public SingleWorldListener(JavaPlugin plugin) throws Exception {
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle").getRealMethod();

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.bukkit.listener;
import com.google.inject.Inject;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.GeneratorWrapper;
@ -36,17 +37,23 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.generator.ChunkGenerator;
import javax.annotation.Nonnull;
@SuppressWarnings("unused")
public class WorldEvents implements Listener {
private final PlotAreaManager plotAreaManager;
@Inject public WorldEvents(@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWorldInit(WorldInitEvent event) {
World world = event.getWorld();
String name = world.getName();
PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
if (manager instanceof SinglePlotAreaManager) {
SinglePlotAreaManager single = (SinglePlotAreaManager) manager;
if (this.plotAreaManager instanceof SinglePlotAreaManager) {
final SinglePlotAreaManager single = (SinglePlotAreaManager) this.plotAreaManager;
if (single.isWorld(name)) {
world.setKeepSpawnInMemory(false);
return;
@ -56,7 +63,7 @@ public class WorldEvents implements Listener {
if (gen instanceof GeneratorWrapper) {
PlotSquared.get().loadWorld(name, (GeneratorWrapper<?>) gen);
} else {
PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen));
PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen, this.plotAreaManager));
}
}
}

View File

@ -25,14 +25,15 @@
*/
package com.plotsquared.bukkit.managers;
import com.google.inject.Singleton;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.util.PlatformWorldManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
@ -44,13 +45,13 @@ import java.util.List;
* Default Bukkit world manager. It will handle world creation by
* registering the generator in bukkit.yml
*/
public class BukkitWorldManager implements PlatformWorldManager<World> {
@Singleton public class BukkitWorldManager implements PlatformWorldManager<World> {
@Override public void initialize() {
}
@Override @Nullable
public World handleWorldCreation(@NotNull String worldName, @Nullable String generator) {
public World handleWorldCreation(@Nonnull String worldName, @Nullable String generator) {
this.setGenerator(worldName, generator);
final WorldCreator wc = new WorldCreator(worldName);
wc.environment(World.Environment.NORMAL);

View File

@ -25,9 +25,10 @@
*/
package com.plotsquared.bukkit.managers;
import com.google.inject.Singleton;
import org.bukkit.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import se.hyperver.hyperverse.Hyperverse;
import se.hyperver.hyperverse.world.WorldConfiguration;
import se.hyperver.hyperverse.world.WorldConfigurationBuilder;
@ -38,10 +39,10 @@ import se.hyperver.hyperverse.world.WorldType;
* Hyperverse specific manager that creates worlds
* using Hyperverse's API
*/
public class HyperverseWorldManager extends BukkitWorldManager {
@Singleton public class HyperverseWorldManager extends BukkitWorldManager {
@Override @Nullable
public World handleWorldCreation(@NotNull String worldName, @Nullable String generator) {
public World handleWorldCreation(@Nonnull String worldName, @Nullable String generator) {
// First let Bukkit register the world
this.setGenerator(worldName, generator);
// Create the world

View File

@ -25,19 +25,20 @@
*/
package com.plotsquared.bukkit.managers;
import com.google.inject.Singleton;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Multiverse specific manager that informs Multiverse of
* world creation by executing a console command
*/
public class MultiverseWorldManager extends BukkitWorldManager {
@Singleton public class MultiverseWorldManager extends BukkitWorldManager {
@Override @Nullable
public World handleWorldCreation(@NotNull final String worldName, @Nullable final String generator) {
public World handleWorldCreation(@Nonnull final String worldName, @Nullable final String generator) {
// First let Bukkit register the world
this.setGenerator(worldName, generator);
// Then we send the console command

View File

@ -64,7 +64,7 @@ public class Placeholders extends PlaceholderExpansion {
}
@Override public String onPlaceholderRequest(Player p, String identifier) {
final PlotPlayer pl = PlotSquared.imp().getPlayerManager().getPlayerIfExists(p.getUniqueId());
final PlotPlayer pl = PlotSquared.platform().getPlayerManager().getPlayerIfExists(p.getUniqueId());
if (pl == null) {
return "";

View File

@ -27,7 +27,7 @@ package com.plotsquared.bukkit.player;
import com.plotsquared.core.player.OfflinePlotPlayer;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.UUID;
@ -45,7 +45,7 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
this.player = player;
}
@NotNull @Override public UUID getUUID() {
@Nonnull @Override public UUID getUUID() {
return this.player.getUniqueId();
}

View File

@ -34,7 +34,9 @@ import com.plotsquared.core.events.TeleportCause;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotWeather;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MathMan;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extension.platform.Actor;
@ -51,7 +53,8 @@ import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.RegisteredListener;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Set;
@ -66,27 +69,36 @@ import static com.sk89q.worldedit.world.gamemode.GameModes.SURVIVAL;
public class BukkitPlayer extends PlotPlayer<Player> {
private static boolean CHECK_EFFECTIVE = true;
private final EconHandler econHandler;
public final Player player;
private boolean offline;
private String name;
/**
* <p>Please do not use this method. Instead use
* BukkitUtil.getPlayer(Player), as it caches player objects.</p>
*
* @param player Bukkit player instance
*/
public BukkitPlayer(@NotNull final Player player) {
this(player, false);
public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher,
@Nonnull final Player player, @Nullable final EconHandler econHandler) {
this(plotAreaManager, eventDispatcher, player, false, econHandler);
}
public BukkitPlayer(@NotNull final Player player, final boolean offline) {
this(player, offline, true);
public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final EventDispatcher eventDispatcher,
@Nonnull final Player player, final boolean offline, @Nullable final EconHandler econHandler) {
this(plotAreaManager, eventDispatcher, player, offline, true, econHandler);
}
public BukkitPlayer(@NotNull final Player player, final boolean offline, final boolean realPlayer) {
public BukkitPlayer(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final
EventDispatcher eventDispatcher, @Nonnull final Player player, final boolean offline,
final boolean realPlayer, @Nullable final EconHandler econHandler) {
super(plotAreaManager, eventDispatcher, econHandler);
this.player = player;
this.offline = offline;
this.econHandler = econHandler;
if (realPlayer) {
super.populatePersistentMetaMap();
}
@ -100,12 +112,12 @@ public class BukkitPlayer extends PlotPlayer<Player> {
return this.player;
}
@NotNull @Override public Location getLocation() {
@Nonnull @Override public Location getLocation() {
final Location location = super.getLocation();
return location == null ? BukkitUtil.getLocation(this.player) : location;
}
@NotNull @Override public UUID getUUID() {
@Nonnull @Override public UUID getUUID() {
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" +
@ -122,7 +134,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
return this.player.getLastPlayed();
}
@Override public boolean canTeleport(@NotNull final Location location) {
@Override public boolean canTeleport(@Nonnull final Location location) {
final org.bukkit.Location to = BukkitUtil.getLocation(location);
final org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
@ -135,10 +147,10 @@ public class BukkitPlayer extends PlotPlayer<Player> {
return true;
}
private void callEvent(@NotNull final Event event) {
private void callEvent(@Nonnull final Event event) {
final RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (final RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) {
if (listener.getPlugin().getName().equals(PlotSquared.platform().getPluginName())) {
continue;
}
try {
@ -150,8 +162,8 @@ public class BukkitPlayer extends PlotPlayer<Player> {
}
@Override public boolean hasPermission(@NotNull final String permission) {
if (this.offline && EconHandler.getEconHandler() != null) {
return EconHandler.getEconHandler().hasPermission(getName(), permission);
if (this.offline && this.econHandler != null) {
return this.econHandler.hasPermission(getName(), permission);
}
return this.player.hasPermission(permission);
}
@ -221,12 +233,12 @@ public class BukkitPlayer extends PlotPlayer<Player> {
}
@Override
public void teleport(@NotNull final Location location, @NotNull final TeleportCause cause) {
public void teleport(@Nonnull final Location location, @Nonnull final TeleportCause cause) {
if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) {
return;
}
final org.bukkit.Location bukkitLocation =
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5,
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX() + 0.5,
location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch());
PaperLib.teleportAsync(player, bukkitLocation, getTeleportCause(cause));
}
@ -244,7 +256,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
@Override public void setCompassTarget(Location location) {
this.player.setCompassTarget(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(),
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorldName()), location.getX(),
location.getY(), location.getZ()));
}
@ -252,7 +264,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
return BukkitUtil.getLocationFull(this.player);
}
@Override public void setWeather(@NotNull final PlotWeather weather) {
@Override public void setWeather(@Nonnull final PlotWeather weather) {
switch (weather) {
case CLEAR:
this.player.setPlayerWeather(WeatherType.CLEAR);
@ -267,7 +279,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
}
}
@NotNull @Override public com.sk89q.worldedit.world.gamemode.GameMode getGameMode() {
@Override public com.sk89q.worldedit.world.gamemode.GameMode getGameMode() {
switch (this.player.getGameMode()) {
case ADVENTURE:
return ADVENTURE;
@ -282,7 +294,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
}
@Override
public void setGameMode(@NotNull final com.sk89q.worldedit.world.gamemode.GameMode gameMode) {
public void setGameMode(final com.sk89q.worldedit.world.gamemode.GameMode gameMode) {
if (ADVENTURE.equals(gameMode)) {
this.player.setGameMode(GameMode.ADVENTURE);
} else if (CREATIVE.equals(gameMode)) {
@ -310,7 +322,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
this.player.setAllowFlight(fly);
}
@Override public void playMusic(@NotNull final Location location, @NotNull final ItemType id) {
@Override public void playMusic(@Nonnull final Location location, @Nonnull final ItemType id) {
if (id == ItemTypes.AIR) {
// Let's just stop all the discs because why not?
for (final Sound sound : Arrays.stream(Sound.values())
@ -344,7 +356,7 @@ public class BukkitPlayer extends PlotPlayer<Player> {
}
public PlayerTeleportEvent.TeleportCause getTeleportCause(@NotNull final TeleportCause cause) {
public PlayerTeleportEvent.TeleportCause getTeleportCause(@Nonnull final TeleportCause cause) {
switch (cause) {
case COMMAND:
return PlayerTeleportEvent.TeleportCause.COMMAND;

View File

@ -25,33 +25,51 @@
*/
package com.plotsquared.bukkit.player;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.PlayerManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import java.util.UUID;
/**
* Player manager providing {@link BukkitPlayer Bukkit players}
*/
public class BukkitPlayerManager extends PlayerManager<BukkitPlayer, Player> {
@Singleton public class BukkitPlayerManager extends PlayerManager<BukkitPlayer, Player> {
@NotNull @Override public BukkitPlayer getPlayer(@NotNull final Player object) {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public BukkitPlayerManager(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
@Nonnull @Override public BukkitPlayer getPlayer(@Nonnull final Player object) {
try {
return getPlayer(object.getUniqueId());
} catch (final NoSuchPlayerException exception) {
return new BukkitPlayer(object, object.isOnline(), false);
return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, object,
object.isOnline(), false, this.econHandler);
}
}
@Override @NotNull public BukkitPlayer createPlayer(@NotNull final UUID uuid) {
@Override @Nonnull public BukkitPlayer createPlayer(@Nonnull final UUID uuid) {
final Player player = Bukkit.getPlayer(uuid);
if (player == null || !player.isOnline()) {
throw new NoSuchPlayerException(uuid);
}
return new BukkitPlayer(player);
return new BukkitPlayer(this.plotAreaManager, this.eventDispatcher, player, this.econHandler);
}
@Nullable @Override public BukkitOfflinePlayer getOfflinePlayer(@Nullable final UUID uuid) {
@ -61,7 +79,7 @@ public class BukkitPlayerManager extends PlayerManager<BukkitPlayer, Player> {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid));
}
@NotNull @Override public BukkitOfflinePlayer getOfflinePlayer(@NotNull final String username) {
@Nonnull @Override public BukkitOfflinePlayer getOfflinePlayer(@Nonnull final String username) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(username));
}

View File

@ -27,11 +27,9 @@ package com.plotsquared.bukkit.queue;
import com.plotsquared.bukkit.schematic.StateWrapper;
import com.plotsquared.bukkit.util.BukkitBlockUtil;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.queue.BasicLocalBlockQueue;
import com.plotsquared.core.util.BlockUtil;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
@ -42,7 +40,6 @@ import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import io.papermc.lib.PaperLib;
import lombok.NonNull;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
@ -51,6 +48,7 @@ import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.Container;
import org.bukkit.block.data.BlockData;
import javax.annotation.Nonnull;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
@ -85,8 +83,6 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue {
World worldObj = Bukkit.getWorld(getWorld());
if (worldObj != null) {
worldObj.refreshChunk(x, z);
} else {
PlotSquared.debug("Error Refreshing Chunk");
}
}
@ -109,8 +105,6 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue {
world.regenerate(region, editSession);
}
}
} else {
PlotSquared.debug("Error Regenerating Chunk");
}
}
@ -201,12 +195,12 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue {
return chunk;
}
private void setMaterial(@NonNull final BlockState plotBlock, @NonNull final Block block) {
private void setMaterial(@Nonnull final BlockState plotBlock, @Nonnull final Block block) {
Material material = BukkitAdapter.adapt(plotBlock.getBlockType());
block.setType(material, false);
}
private boolean equals(@NonNull final BlockState plotBlock, @NonNull final Block block) {
private boolean equals(@Nonnull final BlockState plotBlock, @Nonnull final Block block) {
return plotBlock.equals(BukkitBlockUtil.get(block));
}

View File

@ -0,0 +1,326 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.queue;
import com.google.common.base.Preconditions;
import com.plotsquared.bukkit.BukkitMain;
import com.sk89q.worldedit.math.BlockVector2;
import io.papermc.lib.PaperLib;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* Utility that allows for the loading and coordination of chunk actions
* <p>
* The coordinator takes in collection of chunk coordinates, loads them
* and allows the caller to specify a sink for the loaded chunks. The
* coordinator will prevent the chunks from being unloaded until the sink
* has fully consumed the chunk
* <p>
* Usage:
* <pre>{@code
* final ChunkCoordinator chunkCoordinator = ChunkCoordinator.builder()
* .inWorld(Objects.requireNonNull(Bukkit.getWorld("world"))).withChunk(BlockVector2.at(0, 0))
* .withConsumer(chunk -> System.out.printf("Got chunk %d;%d", chunk.getX(), chunk.getZ()))
* .withFinalAction(() -> System.out.println("All chunks have been loaded"))
* .withThrowableConsumer(throwable -> System.err.println("Something went wrong... =("))
* .withMaxIterationTime(25L)
* .build();
* chunkCoordinator.subscribeToProgress((coordinator, progress) ->
* System.out.printf("Progress: %.1f", progress * 100.0f));
* chunkCoordinator.start();
* }</pre>
*
* @author Alexander Söderberg
* @see #builder() To create a new coordinator instance
*/
public final class ChunkCoordinator extends BukkitRunnable {
private final List<ProgressSubscriber> progressSubscribers = new LinkedList<>();
private final Queue<BlockVector2> requestedChunks;
private final Queue<Chunk> availableChunks;
private final long maxIterationTime;
private final Plugin plugin;
private final Consumer<Chunk> chunkConsumer;
private final World world;
private final Runnable whenDone;
private final Consumer<Throwable> throwableConsumer;
private final int totalSize;
private AtomicInteger expectedSize;
private int batchSize;
private ChunkCoordinator(final long maxIterationTime, final int initialBatchSize,
@NotNull final Consumer<Chunk> chunkConsumer, @NotNull final World world,
@NotNull final Collection<BlockVector2> requestedChunks, @NotNull final Runnable whenDone,
@NotNull final Consumer<Throwable> throwableConsumer) {
this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks);
this.availableChunks = new LinkedBlockingQueue<>();
this.totalSize = requestedChunks.size();
this.expectedSize = new AtomicInteger(this.totalSize);
this.world = world;
this.batchSize = initialBatchSize;
this.chunkConsumer = chunkConsumer;
this.maxIterationTime = maxIterationTime;
this.whenDone = whenDone;
this.throwableConsumer = throwableConsumer;
this.plugin = JavaPlugin.getPlugin(BukkitMain.class);
}
/**
* Create a new {@link ChunkCoordinator} instance
*
* @return Coordinator builder instance
*/
@NotNull public static ChunkCoordinatorBuilder builder() {
return new ChunkCoordinatorBuilder();
}
/**
* Start the coordinator instance
*/
public void start() {
// Request initial batch
this.requestBatch();
// Wait until next tick to give the chunks a chance to be loaded
this.runTaskTimer(this.plugin, 1L, 1L);
}
@Override public void run() {
Chunk chunk = this.availableChunks.poll();
if (chunk == null) {
return;
}
long iterationTime;
int processedChunks = 0;
do {
final long start = System.currentTimeMillis();
try {
this.chunkConsumer.accept(chunk);
} catch (final Throwable throwable) {
this.throwableConsumer.accept(throwable);
}
this.freeChunk(chunk);
processedChunks++;
final long end = System.currentTimeMillis();
// Update iteration time
iterationTime = end - start;
} while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime
&& (chunk = availableChunks.poll()) != null);
if (processedChunks < this.batchSize) {
// Adjust batch size based on the amount of processed chunks per tick
this.batchSize = processedChunks;
}
final int expected = this.expectedSize.addAndGet(-processedChunks);
final float progress = ((float) totalSize - (float) expected) / (float) totalSize;
for (final ProgressSubscriber subscriber : this.progressSubscribers) {
subscriber.notifyProgress(this, progress);
}
if (expected <= 0) {
try {
this.whenDone.run();
} catch (final Throwable throwable) {
this.throwableConsumer.accept(throwable);
}
this.cancel();
} else {
if (this.availableChunks.size() < processedChunks) {
this.requestBatch();
}
}
}
private void requestBatch() {
BlockVector2 chunk;
for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) {
// This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent
PaperLib.getChunkAtAsync(this.world, chunk.getX(), chunk.getZ(), true, true)
.whenComplete((chunkObject, throwable) -> {
if (throwable != null) {
throwable.printStackTrace();
// We want one less because this couldn't be processed
this.expectedSize.decrementAndGet();
} else {
this.processChunk(chunkObject);
}
});
}
}
private void processChunk(@NotNull final Chunk chunk) {
if (!chunk.isLoaded()) {
throw new IllegalArgumentException(
String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
}
chunk.addPluginChunkTicket(this.plugin);
this.availableChunks.add(chunk);
}
private void freeChunk(@NotNull final Chunk chunk) {
if (!chunk.isLoaded()) {
throw new IllegalArgumentException(
String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ()));
}
chunk.removePluginChunkTicket(this.plugin);
}
/**
* Get the amount of remaining chunks (at the time of the method call)
*
* @return Snapshot view of remaining chunk count
*/
public int getRemainingChunks() {
return this.expectedSize.get();
}
/**
* Get the amount of requested chunks
*
* @return Requested chunk count
*/
public int getTotalChunks() {
return this.totalSize;
}
/**
* Subscribe to coordinator progress updates
*
* @param subscriber Subscriber
*/
public void subscribeToProgress(@NotNull final ChunkCoordinator.ProgressSubscriber subscriber) {
this.progressSubscribers.add(subscriber);
}
@FunctionalInterface
public interface ProgressSubscriber {
/**
* Notify about a progress update in the coordinator
*
* @param coordinator Coordinator instance that triggered the notification
* @param progress Progress in the range [0, 1]
*/
void notifyProgress(@NotNull final ChunkCoordinator coordinator, final float progress);
}
public static final class ChunkCoordinatorBuilder {
private final List<BlockVector2> requestedChunks = new LinkedList<>();
private Consumer<Throwable> throwableConsumer = Throwable::printStackTrace;
private World world;
private Consumer<Chunk> chunkConsumer;
private Runnable whenDone = () -> {
};
private long maxIterationTime = 60; // A little over 1 tick;
private int initialBatchSize = 4;
private ChunkCoordinatorBuilder() {
}
@NotNull public ChunkCoordinatorBuilder inWorld(@NotNull final World world) {
this.world = Preconditions.checkNotNull(world, "World may not be null");
return this;
}
@NotNull
public ChunkCoordinatorBuilder withChunk(@NotNull final BlockVector2 chunkLocation) {
this.requestedChunks
.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null"));
return this;
}
@NotNull public ChunkCoordinatorBuilder withChunks(
@NotNull final Collection<BlockVector2> chunkLocations) {
chunkLocations.forEach(this::withChunk);
return this;
}
@NotNull
public ChunkCoordinatorBuilder withConsumer(@NotNull final Consumer<Chunk> chunkConsumer) {
this.chunkConsumer =
Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null");
return this;
}
@NotNull public ChunkCoordinatorBuilder withFinalAction(@NotNull final Runnable whenDone) {
this.whenDone = Preconditions.checkNotNull(whenDone, "Final action may not be null");
return this;
}
@NotNull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) {
Preconditions
.checkArgument(maxIterationTime > 0, "Max iteration time must be positive");
this.maxIterationTime = maxIterationTime;
return this;
}
@NotNull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) {
Preconditions
.checkArgument(initialBatchSize > 0, "Initial batch size must be positive");
this.initialBatchSize = initialBatchSize;
return this;
}
@NotNull public ChunkCoordinatorBuilder withThrowableConsumer(
@NotNull final Consumer<Throwable> throwableConsumer) {
this.throwableConsumer =
Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null");
return this;
}
@NotNull public ChunkCoordinator build() {
Preconditions.checkNotNull(this.world, "No world was supplied");
Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied");
Preconditions.checkNotNull(this.whenDone, "No final action was supplied");
Preconditions
.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied");
return new ChunkCoordinator(this.maxIterationTime, this.initialBatchSize,
this.chunkConsumer, this.world, this.requestedChunks, this.whenDone,
this.throwableConsumer);
}
}
}

View File

@ -46,7 +46,7 @@ import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Arrays;
@ -62,7 +62,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
@Getter @Setter private ChunkData chunkData = null;
public GenChunk() {
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15));
this.biomes = Biome.values();
}
@ -135,7 +135,7 @@ public class GenChunk extends ScopedLocalBlockQueue {
return false;
}
@Override public boolean setBlock(int x, int y, int z, @NotNull Pattern pattern) {
@Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) {
return setBlock(x, y, z, PatternUtil
.apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z));
}
@ -196,11 +196,11 @@ public class GenChunk extends ScopedLocalBlockQueue {
}
@Override public Location getMax() {
return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
return Location.at(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
}
@Override public Location getMin() {
return new Location(getWorld(), getX() << 4, 0, getZ() << 4);
return Location.at(getWorld(), getX() << 4, 0, getZ() << 4);
}
public GenChunk clone() {

View File

@ -25,14 +25,22 @@
*/
package com.plotsquared.bukkit.schematic;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.jnbt.CompoundTag;
import javax.annotation.Nonnull;
/**
* Schematic Handler.
*/
public class BukkitSchematicHandler extends SchematicHandler {
@Singleton public class BukkitSchematicHandler extends SchematicHandler {
@Inject public BukkitSchematicHandler(@Nonnull final WorldUtil worldUtil) {
super(worldUtil);
}
@Override
public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) {

View File

@ -25,9 +25,9 @@
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.listener.WEExtent;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.entity.EntityCategories;
@ -54,7 +54,7 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
public class BukkitChunkManager extends ChunkManager {
@Singleton public class BukkitChunkManager extends ChunkManager {
public static boolean isIn(CuboidRegion region, int x, int z) {
return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX()
@ -79,8 +79,8 @@ public class BukkitChunkManager extends ChunkManager {
BukkitWorld bukkitWorld1 = new BukkitWorld(world1);
BukkitWorld bukkitWorld2 = new BukkitWorld(world2);
LocalBlockQueue queue1 = GlobalBlockQueue.IMP.getNewQueue(worldName1, false);
LocalBlockQueue queue2 = GlobalBlockQueue.IMP.getNewQueue(worldName2, false);
LocalBlockQueue queue1 = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName1, false);
LocalBlockQueue queue2 = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName2, false);
for (int x = Math.max(r1.getMinimumPoint().getX(), sx);
x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) {

View File

@ -25,9 +25,10 @@
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.player.BukkitOfflinePlayer;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.player.OfflinePlotPlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.util.EconHandler;
@ -35,11 +36,18 @@ import com.plotsquared.core.util.PermHandler;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import javax.annotation.Nullable;
public class BukkitEconHandler extends EconHandler {
@Singleton public class BukkitEconHandler extends EconHandler {
private Economy econ;
private final PermHandler permHandler;
@Inject public BukkitEconHandler(@Nullable final PermHandler permHandler) {
this.permHandler = permHandler;
}
@Override
public boolean init() {
if (this.econ == null) {
@ -83,8 +91,8 @@ public class BukkitEconHandler extends EconHandler {
* @deprecated Use {@link PermHandler#hasPermission(String, String, String)} instead
*/
@Deprecated @Override public boolean hasPermission(String world, String player, String perm) {
if (PlotSquared.imp().getPermissionHandler() != null) {
return PlotSquared.imp().getPermissionHandler().hasPermission(world, player, perm);
if (this.permHandler != null) {
return this.permHandler.hasPermission(world, player, perm);
} else {
return false;
}

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.PlotInventory;
@ -45,7 +46,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class BukkitInventoryUtil extends InventoryUtil {
@Singleton public class BukkitInventoryUtil extends InventoryUtil {
@Override public void open(PlotInventory inv) {
BukkitPlayer bp = (BukkitPlayer) inv.player;

View File

@ -25,12 +25,13 @@
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Singleton;
import com.plotsquared.core.util.PermHandler;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
public class BukkitPermHandler extends PermHandler {
@Singleton public class BukkitPermHandler extends PermHandler {
private Permission perms;

View File

@ -25,7 +25,9 @@
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.BukkitMain;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.generator.AugmentedUtils;
import com.plotsquared.core.location.Location;
@ -33,7 +35,6 @@ import com.plotsquared.core.location.PlotLoc;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
@ -56,7 +57,10 @@ import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
@ -74,7 +78,13 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER;
import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE;
public class BukkitRegionManager extends RegionManager {
@Singleton public class BukkitRegionManager extends RegionManager {
private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName());
@Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager) {
super(chunkManager);
}
public static boolean isIn(CuboidRegion region, int x, int z) {
return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX()
@ -91,10 +101,8 @@ public class BukkitRegionManager extends RegionManager {
} else {
final Semaphore semaphore = new Semaphore(1);
try {
PlotSquared.debug("Attempting to make an asynchronous call to getLoadedChunks."
+ " Will halt the calling thread until completed.");
semaphore.acquire();
Bukkit.getScheduler().runTask(BukkitMain.getPlugin(BukkitMain.class), () -> {
Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> {
for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world))
.getLoadedChunks()) {
BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5);
@ -198,14 +206,14 @@ public class BukkitRegionManager extends RegionManager {
final CuboidRegion region =
RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());
final World oldWorld = Bukkit.getWorld(pos1.getWorldName());
final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld);
final World newWorld = Bukkit.getWorld(newPos.getWorld());
final World newWorld = Bukkit.getWorld(newPos.getWorldName());
assert newWorld != null;
assert oldWorld != null;
final String newWorldName = newWorld.getName();
final ContentMap map = new ContentMap();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false);
final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorldName, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override public void run(int[] value) {
int bx = value[2];
@ -236,7 +244,7 @@ public class BukkitRegionManager extends RegionManager {
}
}
queue.enqueue();
GlobalBlockQueue.IMP.addEmptyTask(() -> {
PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(() -> {
//map.restoreBlocks(newWorld, 0, 0);
map.restoreEntities(newWorld, relX, relZ);
TaskManager.runTask(whenDone);
@ -248,7 +256,7 @@ public class BukkitRegionManager extends RegionManager {
@Override
public boolean regenerateRegion(final Location pos1, final Location pos2,
final boolean ignoreAugment, final Runnable whenDone) {
final String world = pos1.getWorld();
final String world = pos1.getWorldName();
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
@ -284,8 +292,8 @@ public class BukkitRegionManager extends RegionManager {
if (chunkObj == null) {
return;
}
final LocalBlockQueue queue =
GlobalBlockQueue.IMP.getNewQueue(world, false);
final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue()
.getNewQueue(world, false);
if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) {
AugmentedUtils.bypass(ignoreAugment,
() -> queue.regenChunkSafe(chunk.getX(), chunk.getZ()));
@ -401,7 +409,7 @@ public class BukkitRegionManager extends RegionManager {
}
@Override public void clearAllEntities(Location pos1, Location pos2) {
String world = pos1.getWorld();
String world = pos1.getWorldName();
List<Entity> entities = BukkitUtil.getEntities(world);
int bx = pos1.getX();
int bz = pos1.getZ();
@ -428,8 +436,8 @@ public class BukkitRegionManager extends RegionManager {
RegionUtil.createRegion(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ());
CuboidRegion region2 =
RegionUtil.createRegion(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ());
final World world1 = Bukkit.getWorld(bot1.getWorld());
final World world2 = Bukkit.getWorld(bot2.getWorld());
final World world1 = Bukkit.getWorld(bot1.getWorldName());
final World world2 = Bukkit.getWorld(bot2.getWorldName());
checkNotNull(world1, "Critical error during swap.");
checkNotNull(world2, "Critical error during swap.");
int relX = bot2.getX() - bot1.getX();
@ -445,7 +453,7 @@ public class BukkitRegionManager extends RegionManager {
BukkitChunkManager.swapChunk(world1, world2, chunk1, chunk2, region1, region2));
}
}
GlobalBlockQueue.IMP.addEmptyTask(() -> {
PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(() -> {
for (ContentMap map : maps) {
map.restoreEntities(world1, 0, 0);
TaskManager.runTaskLater(whenDone, 1);
@ -456,16 +464,17 @@ public class BukkitRegionManager extends RegionManager {
@Override
public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome,
final String world, final Runnable whenDone) {
Location pos1 = new Location(world, region.getMinimumPoint().getX() - extendBiome,
Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome,
region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome);
Location pos2 = new Location(world, region.getMaximumPoint().getX() + extendBiome,
Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome,
region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome);
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue()
.getNewQueue(world, false);
ChunkManager.chunkTask(pos1, pos2, new RunnableVal<int[]>() {
@Override public void run(int[] value) {
BlockVector2 loc = BlockVector2.at(value[0], value[1]);
ChunkManager.manager.loadChunk(world, loc, false).thenRun(() -> {
PlotSquared.platform().getChunkManager().loadChunk(world, loc, false).thenRun(() -> {
MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome);
queue.refreshChunk(value[0], value[1]);
});

View File

@ -25,14 +25,20 @@
*/
package com.plotsquared.bukkit.util;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.SetupObject;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.util.SetupUtils;
import io.papermc.lib.PaperLib;
@ -42,13 +48,27 @@ import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
public class BukkitSetupUtils extends SetupUtils {
@Singleton public class BukkitSetupUtils extends SetupUtils {
private final PlotAreaManager plotAreaManager;
private final YamlConfiguration worldConfiguration;
private final File worldFile;
@Inject public BukkitSetupUtils(@Nonnull final PlotAreaManager plotAreaManager,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@WorldFile @Nonnull final File worldFile) {
this.plotAreaManager = plotAreaManager;
this.worldConfiguration = worldConfiguration;
this.worldFile = worldFile;
}
@Override public void updateGenerators() {
if (!SetupUtils.generators.isEmpty()) {
@ -66,7 +86,7 @@ public class BukkitSetupUtils extends SetupUtils {
if (generator instanceof GeneratorWrapper<?>) {
wrapped = (GeneratorWrapper<?>) generator;
} else {
wrapped = new BukkitPlotGenerator(testWorld, generator);
wrapped = new BukkitPlotGenerator(testWorld, generator, this.plotAreaManager);
}
SetupUtils.generators.put(name, wrapped);
}
@ -99,7 +119,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
@Deprecated @Override public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators();
this.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
String world = object.world;
PlotAreaType type = object.type;
@ -107,11 +127,10 @@ public class BukkitSetupUtils extends SetupUtils {
switch (type) {
case PARTIAL: {
if (object.id != null) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(worldPath);
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
@ -151,26 +170,21 @@ public class BukkitSetupUtils extends SetupUtils {
}
case AUGMENTED: {
if (!object.plotManager.endsWith(":single")) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
if (steps.length != 0) {
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
PlotSquared.get().worlds
.set("worlds." + world + ".generator.type", object.type.toString());
PlotSquared.get().worlds
.set("worlds." + world + ".generator.terrain", object.terrain.toString());
PlotSquared.get().worlds
.set("worlds." + world + ".generator.plugin", object.plotManager);
this.worldConfiguration.set("worlds." + world + ".generator.type", object.type.toString());
this.worldConfiguration.set("worlds." + world + ".generator.terrain", object.terrain.toString());
this.worldConfiguration.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator
.equals(object.plotManager)) {
PlotSquared.get().worlds
.set("worlds." + world + ".generator.init", object.setupGenerator);
this.worldConfiguration.set("worlds." + world + ".generator.init", object.setupGenerator);
}
}
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
@ -181,11 +195,10 @@ public class BukkitSetupUtils extends SetupUtils {
}
case NORMAL: {
if (steps.length != 0) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
@ -195,12 +208,12 @@ public class BukkitSetupUtils extends SetupUtils {
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
this.worldConfiguration.save(this.worldFile);
} catch (IOException e) {
e.printStackTrace();
}
Objects.requireNonNull(PlotSquared.imp()).getWorldManager()
Objects.requireNonNull(PlotSquared.platform()).getWorldManager()
.handleWorldCreation(object.world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
@ -211,7 +224,7 @@ public class BukkitSetupUtils extends SetupUtils {
}
@Override public String setupWorld(PlotAreaBuilder builder) {
SetupUtils.manager.updateGenerators();
this.updateGenerators();
ConfigurationNode[] steps = builder.settingsNodesWrapper() == null ?
new ConfigurationNode[0] : builder.settingsNodesWrapper().getSettingsNodes();
String world = builder.worldName();
@ -220,11 +233,11 @@ public class BukkitSetupUtils extends SetupUtils {
switch (type) {
case PARTIAL: {
if (builder.areaName() != null) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
this.worldConfiguration.getConfigurationSection(worldPath);
String areaName = builder.areaName() + "-" + builder.minimumId() + "-" + builder.maximumId();
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
@ -264,25 +277,25 @@ public class BukkitSetupUtils extends SetupUtils {
}
case AUGMENTED: {
if (!builder.plotManager().endsWith(":single")) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
if (steps.length != 0) {
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
}
PlotSquared.get().worlds
this.worldConfiguration
.set("worlds." + world + ".generator.type", builder.plotAreaType().toString());
PlotSquared.get().worlds
this.worldConfiguration
.set("worlds." + world + ".generator.terrain", builder.terrainType().toString());
PlotSquared.get().worlds
this.worldConfiguration
.set("worlds." + world + ".generator.plugin", builder.plotManager());
if (builder.generatorName() != null && !builder.generatorName()
.equals(builder.plotManager())) {
PlotSquared.get().worlds
this.worldConfiguration
.set("worlds." + world + ".generator.init", builder.generatorName());
}
}
@ -294,11 +307,11 @@ public class BukkitSetupUtils extends SetupUtils {
}
case NORMAL: {
if (steps.length != 0) {
if (!PlotSquared.get().worlds.contains(worldPath)) {
PlotSquared.get().worlds.createSection(worldPath);
if (!this.worldConfiguration.contains(worldPath)) {
this.worldConfiguration.createSection(worldPath);
}
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection(worldPath);
this.worldConfiguration.getConfigurationSection(worldPath);
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
@ -308,12 +321,12 @@ public class BukkitSetupUtils extends SetupUtils {
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
this.worldConfiguration.save(this.worldFile);
} catch (IOException e) {
e.printStackTrace();
}
Objects.requireNonNull(PlotSquared.imp()).getWorldManager()
Objects.requireNonNull(PlotSquared.platform()).getWorldManager()
.handleWorldCreation(builder.worldName(), builder.generatorName());
if (Bukkit.getWorld(world) != null) {

View File

@ -25,15 +25,17 @@
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.BukkitMain;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.core.util.task.TaskManager;
import org.bukkit.Bukkit;
public class BukkitTaskManager extends TaskManager {
@Singleton public class BukkitTaskManager extends TaskManager {
private final BukkitMain bukkitMain;
private final BukkitPlatform bukkitMain;
public BukkitTaskManager(BukkitMain bukkitMain) {
@Inject public BukkitTaskManager(BukkitPlatform bukkitMain) {
this.bukkitMain = bukkitMain;
}

View File

@ -25,7 +25,9 @@
*/
package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.BukkitMain;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.bukkit.BukkitPlatform;
import com.plotsquared.bukkit.player.BukkitPlayer;
import com.plotsquared.bukkit.player.BukkitPlayerManager;
import com.plotsquared.core.PlotSquared;
@ -38,6 +40,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.BlockUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.StringComparison;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.RunnableVal;
@ -52,11 +55,11 @@ import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import io.papermc.lib.PaperLib;
import lombok.NonNull;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.Template;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
@ -98,8 +101,10 @@ import org.bukkit.entity.Snowman;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.WaterMob;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
@ -113,7 +118,9 @@ import java.util.function.IntConsumer;
import java.util.stream.Stream;
@SuppressWarnings({"unused", "WeakerAccess"})
public class BukkitUtil extends WorldUtil {
@Singleton public class BukkitUtil extends WorldUtil {
private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName());
public static final BukkitAudiences BUKKIT_AUDIENCES = BukkitAudiences.create(BukkitMain.getPlugin(BukkitMain.class));
public static final LegacyComponentSerializer LEGACY_COMPONENT_SERIALIZER = LegacyComponentSerializer.legacy();
@ -125,20 +132,25 @@ public class BukkitUtil extends WorldUtil {
private static Player lastPlayer = null;
private static BukkitPlayer lastPlotPlayer = null;
@Inject public BukkitUtil(@Nonnull final RegionManager regionManager) {
super(regionManager);
}
public static void removePlayer(UUID uuid) {
lastPlayer = null;
lastPlotPlayer = null;
// Make sure that it's removed internally
PlotSquared.imp().getPlayerManager().removePlayer(uuid);
PlotSquared.platform().getPlayerManager().removePlayer(uuid);
}
public static PlotPlayer<Player> getPlayer(@NonNull final OfflinePlayer op) {
public static PlotPlayer<Player> getPlayer(@Nonnull final OfflinePlayer op) {
if (op.isOnline()) {
return getPlayer(op.getPlayer());
}
final Player player = OfflinePlayerUtil.loadPlayer(op);
player.loadData();
return new BukkitPlayer(player, true);
return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(),
PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler());
}
/**
@ -255,39 +267,39 @@ public class BukkitUtil extends WorldUtil {
return BukkitUtil.getPlayer(player).getPlotCount(world);
}
public static BukkitPlayer getPlayer(@NonNull final Player player) {
public static BukkitPlayer getPlayer(@Nonnull final Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
final PlayerManager<?, ?> playerManager = PlotSquared.imp().getPlayerManager();
final PlayerManager<?, ?> playerManager = PlotSquared.platform().getPlayerManager();
return ((BukkitPlayerManager) playerManager).getPlayer(player);
}
public static Location getLocation(@NonNull final org.bukkit.Location location) {
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
public static Location getLocation(final org.bukkit.Location location) {
return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()),
MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()));
}
public static Location getLocationFull(@NonNull final org.bukkit.Location location) {
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(),
public static Location getLocationFull(final org.bukkit.Location location) {
return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()),
MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(),
location.getPitch());
}
public static org.bukkit.Location getLocation(@NonNull final Location location) {
return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(),
public static org.bukkit.Location getLocation(@Nonnull final Location location) {
return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(),
location.getY(), location.getZ());
}
public static World getWorld(@NonNull final String string) {
public static World getWorld(@Nonnull final String string) {
return Bukkit.getWorld(string);
}
public static String getWorld(@NonNull final Entity entity) {
public static String getWorld(@Nonnull final Entity entity) {
return entity.getWorld().getName();
}
public static List<Entity> getEntities(@NonNull final String worldName) {
public static List<Entity> getEntities(@Nonnull final String worldName) {
World world = getWorld(worldName);
if (world != null) {
return world.getEntities();
@ -296,21 +308,21 @@ public class BukkitUtil extends WorldUtil {
}
}
public static Location getLocation(@NonNull final Entity entity) {
public static Location getLocation(@Nonnull final Entity entity) {
final org.bukkit.Location location = entity.getLocation();
String world = location.getWorld().getName();
return new Location(world, location.getBlockX(), location.getBlockY(),
return Location.at(world, location.getBlockX(), location.getBlockY(),
location.getBlockZ());
}
@NotNull public static Location getLocationFull(@NonNull final Entity entity) {
@Nonnull public static Location getLocationFull(@Nonnull final Entity entity) {
final org.bukkit.Location location = entity.getLocation();
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()),
return Location.at(location.getWorld().getName(), MathMan.roundInt(location.getX()),
MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(),
location.getPitch());
}
public static Material getMaterial(@NonNull final BlockState plotBlock) {
public static Material getMaterial(@Nonnull final BlockState plotBlock) {
return BukkitAdapter.adapt(plotBlock.getBlockType());
}
@ -322,7 +334,7 @@ public class BukkitUtil extends WorldUtil {
return mat1 == mat2;
}
@Override public boolean isWorld(@NonNull final String worldName) {
@Override public boolean isWorld(@Nonnull final String worldName) {
return getWorld(worldName) != null;
}
@ -336,7 +348,7 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void getHighestBlock(@NonNull final String world, final int x, final int z,
public void getHighestBlock(@Nonnull final String world, final int x, final int z,
final IntConsumer result) {
ensureLoaded(world, x, z, chunk -> {
final World bukkitWorld = getWorld(world);
@ -386,7 +398,7 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void getSign(@NonNull final Location location, final Consumer<String[]> result) {
public void getSign(@Nonnull final Location location, final Consumer<String[]> result) {
ensureLoaded(location, chunk -> {
final Block block = chunk.getWorld().getBlockAt(getLocation(location));
if (block.getState() instanceof Sign) {
@ -396,10 +408,10 @@ public class BukkitUtil extends WorldUtil {
});
}
@Override @Nullable public String[] getSignSynchronous(@NonNull final Location location) {
Block block = getWorld(location.getWorld())
@Override @Nullable public String[] getSignSynchronous(@Nonnull final Location location) {
Block block = getWorld(location.getWorldName())
.getBlockAt(location.getX(), location.getY(), location.getZ());
return TaskManager.IMP.sync(new RunnableVal<String[]>() {
return TaskManager.getImplementation().sync(new RunnableVal<String[]>() {
@Override public void run(String[] value) {
if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState();
@ -409,20 +421,20 @@ public class BukkitUtil extends WorldUtil {
});
}
@Override public Location getSpawn(@NonNull final String world) {
@Override public Location getSpawn(@Nonnull final String world) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(),
return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(),
temp.getYaw(), temp.getPitch());
}
@Override public void setSpawn(@NonNull final Location location) {
final World world = getWorld(location.getWorld());
@Override public void setSpawn(@Nonnull final Location location) {
final World world = getWorld(location.getWorldName());
if (world != null) {
world.setSpawnLocation(location.getX(), location.getY(), location.getZ());
}
}
@Override public void saveWorld(@NonNull final String worldName) {
@Override public void saveWorld(@Nonnull final String worldName) {
final World world = getWorld(worldName);
if (world != null) {
world.save();
@ -430,11 +442,13 @@ public class BukkitUtil extends WorldUtil {
}
@Override @SuppressWarnings("deprecation")
public void setSign(@NotNull final Location location, @NotNull final Caption[] lines,
@NotNull final Template ... replacements) {
public void setSign(@Nonull final Location location, @Nonnull final Caption[] lines,
@Nonnull final Template ... replacements) {
ensureLoaded(location.getWorld(), location.getX(), location.getZ(), chunk -> {
final World world = getWorld(location.getWorld());
final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
final World world = getWorld(worldName);
final Block block = world.getBlockAt(x, y, z);
// block.setType(Material.AIR);
final Material type = block.getType();
if (type != Material.LEGACY_SIGN && type != Material.LEGACY_WALL_SIGN) {
@ -446,13 +460,12 @@ public class BukkitUtil extends WorldUtil {
} else if (world.getBlockAt(location.getX(), location.getY(), location.getZ() - 1).getType().isSolid()) {
facing = BlockFace.SOUTH;
}
if (PlotSquared.get().IMP.getServerVersion()[1] == 13) {
if (PlotSquared.platform().getServerVersion()[1] == 13) {
block.setType(Material.valueOf("WALL_SIGN"), false);
} else {
block.setType(Material.valueOf("OAK_WALL_SIGN"), false);
}
if (!(block.getBlockData() instanceof WallSign)) {
PlotSquared.debug(block.getBlockData().getAsString());
throw new RuntimeException("Something went wrong generating a sign");
}
final Directional sign = (Directional) block.getBlockData();
@ -471,11 +484,11 @@ public class BukkitUtil extends WorldUtil {
});
}
@Override public boolean isBlockSolid(@NonNull final BlockState block) {
@Override public boolean isBlockSolid(@Nonnull final BlockState block) {
return block.getBlockType().getMaterial().isSolid();
}
@Override public String getClosestMatchingName(@NonNull final BlockState block) {
@Override public String getClosestMatchingName(@Nonnull final BlockState block) {
try {
return getMaterial(block).name();
} catch (Exception ignored) {
@ -490,11 +503,11 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void setBiomes(@NonNull final String worldName, @NonNull final CuboidRegion region,
@NonNull final BiomeType biomeType) {
public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region,
@Nonnull final BiomeType biomeType) {
final World world = getWorld(worldName);
if (world == null) {
PlotSquared.log("An error occurred setting the biome because the world was null.");
logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException());
return;
}
final Biome biome = BukkitAdapter.adapt(biomeType);
@ -513,16 +526,16 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void getBlock(@NonNull final Location location, final Consumer<BlockState> result) {
public void getBlock(@Nonnull final Location location, final Consumer<BlockState> result) {
ensureLoaded(location, chunk -> {
final World world = getWorld(location.getWorld());
final World world = getWorld(location.getWorldName());
final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
result.accept(BukkitAdapter.asBlockType(block.getType()).getDefaultState());
});
}
@Override public BlockState getBlockSynchronous(@NonNull final Location location) {
final World world = getWorld(location.getWorld());
@Override public BlockState getBlockSynchronous(@Nonnull final Location location) {
final World world = getWorld(location.getWorldName());
final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
return BukkitAdapter.asBlockType(block.getType()).getDefaultState();
}
@ -608,7 +621,7 @@ public class BukkitUtil extends WorldUtil {
}
break;
default: {
PlotSquared.log(Captions.PREFIX + "Unknown entity category requested: " + category);
logger.error("[P2] Unknown entity category requested: {}", category);
}
break;
}
@ -677,7 +690,7 @@ public class BukkitUtil extends WorldUtil {
consumer.accept(value);
} else {
Bukkit.getScheduler()
.runTask(BukkitMain.getPlugin(BukkitMain.class), () -> consumer.accept(value));
.runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value));
}
}

View File

@ -0,0 +1,85 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.bukkit.util;
import com.google.common.collect.Maps;
import com.plotsquared.core.location.World;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.bukkit.Bukkit;
import javax.annotation.Nonnull;
import java.util.Map;
@EqualsAndHashCode @ToString public class BukkitWorld implements World<org.bukkit.World> {
private static final Map<String, BukkitWorld> worldMap = Maps.newHashMap();
private final org.bukkit.World world;
private BukkitWorld(final org.bukkit.World world) {
this.world = world;
}
/**
* Get a new {@link BukkitWorld} from a world name
*
* @param worldName World name
* @return World instance
*/
@Nonnull public static BukkitWorld of(@Nonnull final String worldName) {
final org.bukkit.World bukkitWorld = Bukkit.getWorld(worldName);
if (bukkitWorld == null) {
throw new IllegalArgumentException(String.format("There is no world with the name '%s'", worldName));
}
return of(bukkitWorld);
}
/**
* Get a new {@link BukkitWorld} from a Bukkit world
*
* @param world Bukkit world
* @return World instance
*/
@Nonnull public static BukkitWorld of(final org.bukkit.World world) {
BukkitWorld bukkitWorld = worldMap.get(world.getName());
if (bukkitWorld != null && bukkitWorld.getPlatformWorld().equals(world)) {
return bukkitWorld;
}
bukkitWorld = new BukkitWorld(world);
worldMap.put(world.getName(), bukkitWorld);
return bukkitWorld;
}
@Override public org.bukkit.World getPlatformWorld() {
return this.world;
}
@Override @Nonnull public String getName() {
return this.world.getName();
}
}

View File

@ -27,7 +27,6 @@ package com.plotsquared.bukkit.util;
import com.plotsquared.bukkit.entity.EntityWrapper;
import com.plotsquared.bukkit.entity.ReplicatingEntityWrapper;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.location.PlotLoc;
import com.sk89q.worldedit.bukkit.BukkitWorld;
@ -38,6 +37,8 @@ import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
@ -46,6 +47,8 @@ import java.util.Set;
public class ContentMap {
private static final Logger logger = LoggerFactory.getLogger("P2/" + ContentMap.class.getSimpleName());
final Set<EntityWrapper> entities;
final Map<PlotLoc, BaseBlock[]> allBlocks;
@ -123,8 +126,7 @@ public class ContentMap {
try {
entity.spawn(world, xOffset, zOffset);
} catch (Exception e) {
PlotSquared.debug("Failed to restore entity (e): " + e.toString());
e.printStackTrace();
logger.error("[P2] Failed to restore entity", e);
}
}
this.entities.clear();

View File

@ -38,7 +38,7 @@ import java.util.ArrayList;
public class SetGenCB {
public static void setGenerator(World world) throws Exception {
SetupUtils.manager.updateGenerators();
PlotSquared.platform().getSetupUtils().updateGenerators();
PlotSquared.get().removePlotAreas(world.getName());
ChunkGenerator gen = world.getGenerator();
if (gen == null) {
@ -72,6 +72,6 @@ public class SetGenCB {
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
}
PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null));
.loadWorld(world.getName(), PlotSquared.platform().getGenerator(world.getName(), null));
}
}

View File

@ -28,14 +28,16 @@ package com.plotsquared.bukkit.util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.PlotVersion;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
@ -44,6 +46,8 @@ import java.net.URL;
public class UpdateUtility implements Listener {
private static final Logger logger = LoggerFactory.getLogger("P2/" + UpdateUtility.class.getSimpleName());
public static PlotVersion internalVersion;
public static String spigotVersion;
public static boolean hasUpdate;
@ -51,7 +55,7 @@ public class UpdateUtility implements Listener {
public final JavaPlugin javaPlugin;
private boolean notify = true;
public UpdateUtility(final JavaPlugin javaPlugin) {
@Inject public UpdateUtility(final JavaPlugin javaPlugin) {
this.javaPlugin = javaPlugin;
internalVersion = PlotSquared.get().getVersion();
}
@ -68,26 +72,22 @@ public class UpdateUtility implements Listener {
.getAsJsonObject();
spigotVersion = result.get("current_version").getAsString();
} catch (IOException e) {
PlotSquared.log(Captions.PREFIX + "&cUnable to check for updates because: " + e);
logger.error("[P2] Unable to check for updates. Error: {}", e.getMessage());
return;
}
if (internalVersion.isLaterVersion(spigotVersion)) {
PlotSquared
.log(Captions.PREFIX + "&6There appears to be a PlotSquared update available!");
PlotSquared.log(
Captions.PREFIX + "&6You are running version " + internalVersion.versionString()
+ ", &6latest version is " + spigotVersion);
PlotSquared
.log(Captions.PREFIX + "&6https://www.spigotmc.org/resources/77506/updates");
logger.info("[P2] There appears to be a PlotSquared update available!");
logger.info("[P2] You are running version {}, the latest version is {}",
internalVersion.versionString(), spigotVersion);
logger.info("[P2] https://www.spigotmc.org/resources/77506/updates");
hasUpdate = true;
if (Settings.UpdateChecker.NOTIFY_ONCE) {
cancelTask();
}
} else if (notify) {
notify = false;
PlotSquared.log(Captions.PREFIX
+ "Congratulations! You are running the latest PlotSquared version.");
logger.info("[P2] Congratulations! You are running the latest PlotSquared version");
}
}, 0L, Settings.UpdateChecker.POLL_RATE * 60 * 20);
}

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.uuid.UUIDService;
import net.luckperms.api.model.user.UserManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
@ -54,7 +54,7 @@ public class BungeePermsUUIDService implements UUIDService {
}
}
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
final UUIDPlayerDB uuiddb = BungeePerms.getInstance().getPermissionsManager().getUUIDPlayerDB();
for (final UUID uuid : uuids) {
@ -68,7 +68,7 @@ public class BungeePermsUUIDService implements UUIDService {
return mappings;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
final UUIDPlayerDB uuiddb = BungeePerms.getInstance().getPermissionsManager().getUUIDPlayerDB();
for (final String username : usernames) {

View File

@ -29,7 +29,7 @@ import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
@ -47,11 +47,11 @@ public class EssentialsUUIDService implements UUIDService {
this.essentials = Essentials.getPlugin(Essentials.class);
}
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
return Collections.emptyList();
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
for (final String username : usernames) {
try {

View File

@ -31,7 +31,7 @@ import net.luckperms.api.LuckPerms;
import net.luckperms.api.model.user.UserManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
@ -53,7 +53,7 @@ public class LuckPermsUUIDService implements UUIDService {
}
}
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
final UserManager userManager = this.luckPerms.getUserManager();
for (final UUID uuid : uuids) {
@ -67,7 +67,7 @@ public class LuckPermsUUIDService implements UUIDService {
return mappings;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
final UserManager userManager = this.luckPerms.getUserManager();
for (final String username : usernames) {

View File

@ -31,7 +31,7 @@ import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
@ -43,7 +43,7 @@ import java.util.UUID;
*/
public class OfflinePlayerUUIDService implements UUIDService {
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
if (Settings.UUID.FORCE_LOWERCASE || Bukkit.getWorlds().isEmpty()) {
return Collections.emptyList(); // This is useless now
}
@ -61,7 +61,7 @@ public class OfflinePlayerUUIDService implements UUIDService {
return wrappers;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> wrappers = new ArrayList<>(usernames.size());
for (final String username : usernames) {
if (Settings.UUID.OFFLINE) {

View File

@ -29,7 +29,7 @@ import com.destroystokyo.paper.profile.PlayerProfile;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
@ -40,7 +40,7 @@ import java.util.UUID;
*/
public class PaperUUIDService implements UUIDService {
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
for (final UUID uuid : uuids) {
final PlayerProfile playerProfile = Bukkit.createProfile(uuid);
@ -51,7 +51,7 @@ public class PaperUUIDService implements UUIDService {
return mappings;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
for (final String username : usernames) {
final PlayerProfile playerProfile = Bukkit.createProfile(username);

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.database.SQLite;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -51,7 +51,7 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
public SQLiteUUIDService(final String fileName) {
this.sqlite =
new SQLite(MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), fileName));
new SQLite(MainUtil.getFile(PlotSquared.platform().getDirectory(), fileName));
try {
this.sqlite.openConnection();
} catch (ClassNotFoundException | SQLException e) {
@ -72,7 +72,7 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
}
}
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
final List<UUIDMapping> mappings = new ArrayList<>(uuids.size());
try (final PreparedStatement statement = getConnection()
.prepareStatement("SELECT `username` FROM `usercache` WHERE `uuid` = ?")) {
@ -90,7 +90,7 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
return mappings;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull List<String> usernames) {
final List<UUIDMapping> mappings = new ArrayList<>(usernames.size());
try (final PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid` FROM `usercache` WHERE `username` = ?")) {
@ -127,7 +127,7 @@ public class SQLiteUUIDService implements UUIDService, Consumer<List<UUIDMapping
*
* @return All read mappings
*/
@NotNull public List<UUIDMapping> getAll() {
@Nonnull public List<UUIDMapping> getAll() {
final List<UUIDMapping> mappings = new LinkedList<>();
try (final PreparedStatement statement = getConnection().prepareStatement("SELECT * FROM `usercache`")) {
try (final ResultSet resultSet = statement.executeQuery()) {

View File

@ -26,14 +26,15 @@
package com.plotsquared.bukkit.uuid;
import com.google.common.util.concurrent.RateLimiter;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.uuid.UUIDMapping;
import com.plotsquared.core.uuid.UUIDService;
import com.sk89q.squirrelid.Profile;
import com.sk89q.squirrelid.resolver.HttpRepositoryService;
import com.sk89q.squirrelid.resolver.ProfileService;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
@ -47,6 +48,8 @@ import java.util.UUID;
@SuppressWarnings("UnstableApiUsage")
public class SquirrelIdUUIDService implements UUIDService {
private static final Logger logger = LoggerFactory.getLogger("P2/" + SquirrelIdUUIDService.class.getSimpleName());
private final ProfileService profileService;
private final RateLimiter rateLimiter;
@ -64,7 +67,7 @@ public class SquirrelIdUUIDService implements UUIDService {
this.rateLimiter = RateLimiter.create(rateLimit / 600.0D);
}
@Override @NotNull public List<UUIDMapping> getNames(@NotNull final List<UUID> uuids) {
@Override @Nonnull public List<UUIDMapping> getNames(@Nonnull final List<UUID> uuids) {
final List<UUIDMapping> results = new ArrayList<>(uuids.size());
this.rateLimiter.acquire(uuids.size());
try {
@ -78,7 +81,9 @@ public class SquirrelIdUUIDService implements UUIDService {
// go through them one by one
//
if (uuids.size() >= 2) {
PlotSquared.debug(Captions.PREFIX + "(UUID) Found invalid UUID in batch. Will try each UUID individually.");
if (Settings.DEBUG) {
logger.info("[P2] (UUID) Found invalid UUID in batch. Will try each UUID individually.");
}
for (final UUID uuid : uuids) {
final List<UUIDMapping> result = this.getNames(Collections.singletonList(uuid));
if (result.isEmpty()) {
@ -86,8 +91,8 @@ public class SquirrelIdUUIDService implements UUIDService {
}
results.add(result.get(0));
}
} else if (uuids.size() == 1) {
PlotSquared.debug(Captions.PREFIX + "(UUID) Found invalid UUID: " + uuids.get(0));
} else if (uuids.size() == 1 && Settings.DEBUG) {
logger.info("[P2] (UUID) Found invalid UUID: {}", uuids.get(0));
}
}
} catch (IOException | InterruptedException e) {
@ -96,7 +101,7 @@ public class SquirrelIdUUIDService implements UUIDService {
return results;
}
@Override @NotNull public List<UUIDMapping> getUUIDs(@NotNull final List<String> usernames) {
@Override @Nonnull public List<UUIDMapping> getUUIDs(@Nonnull final List<String> usernames) {
final List<UUIDMapping> results = new ArrayList<>(usernames.size());
this.rateLimiter.acquire(usernames.size());
try {

View File

@ -1,5 +1,5 @@
name: ${name}
main: com.plotsquared.bukkit.BukkitMain
main: com.plotsquared.bukkit.BukkitPlatform
api-version: "1.13"
version: "${version}"
load: STARTUP

View File

@ -17,11 +17,15 @@ dependencies {
annotationProcessor("org.projectlombok:lombok:1.18.8")
testAnnotationProcessor("org.projectlombok:lombok:1.18.8")
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.72")
implementation("org.jetbrains:annotations:19.0.0")
implementation("org.khelekore:prtree:1.7.0-SNAPSHOT")
// Adventure related stuff
implementation('net.kyori:adventure-api:4.0.0-SNAPSHOT')
implementation('net.kyori:adventure-text-minimessage:3.0.0-SNAPSHOT')
compile("com.google.inject:guice:4.2.3")
compile("com.google.inject.extensions:guice-assistedinject:4.2.3")
compile group: 'com.google.code.findbugs', name: 'annotations', version: '3.0.1'
// logging
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.8.1")
}
sourceCompatibility = 1.8

View File

@ -12,18 +12,36 @@
<version>20200518</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-assistedinject</artifactId>
<version>4.2.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>annotations</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>19.0.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-core</artifactId>
@ -98,6 +116,12 @@
<version>1.7.0-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.8.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -23,12 +23,10 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.api;
package com.plotsquared.core;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Caption;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
@ -38,6 +36,7 @@ import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.query.PlotQuery;
import lombok.NoArgsConstructor;
import java.util.Collections;
@ -64,10 +63,9 @@ import java.util.UUID;
* Gets all plots.
*
* @return all plots
* @see PlotSquared#getPlots()
*/
public Set<Plot> getAllPlots() {
return PlotSquared.get().getPlots();
return PlotQuery.newQuery().allPlots().asSet();
}
/**
@ -76,8 +74,8 @@ import java.util.UUID;
* @param player Player, whose plots to search for
* @return all plots that a player owns
*/
public Set<Plot> getPlayerPlots(PlotPlayer player) {
return PlotSquared.get().getPlots(player);
public Set<Plot> getPlayerPlots(PlotPlayer<?> player) {
return PlotQuery.newQuery().ownedBy(player).asSet();
}
/**
@ -90,26 +88,6 @@ import java.util.UUID;
PlotSquared.get().addPlotArea(plotArea);
}
/**
* Gets the configuration file for this plugin.
*
* @return the configuration file for PlotSquared
* =
*/
public YamlConfiguration getConfig() {
return PlotSquared.get().getConfig();
}
/**
* Gets the PlotSquared storage file.
*
* @return storage configuration
* @see PlotSquared#storage
*/
public YamlConfiguration getStorage() {
return PlotSquared.get().storage;
}
/**
* ChunkManager class contains several useful methods.
* <ul>
@ -124,7 +102,7 @@ import java.util.UUID;
* @see ChunkManager
*/
public ChunkManager getChunkManager() {
return ChunkManager.manager;
return PlotSquared.platform().getInjector().getInstance(ChunkManager.class);
}
/**
@ -133,7 +111,7 @@ import java.util.UUID;
* @return GlobalBlockQueue.IMP
*/
public GlobalBlockQueue getBlockQueue() {
return GlobalBlockQueue.IMP;
return PlotSquared.platform().getGlobalBlockQueue();
}
/**
@ -144,7 +122,7 @@ import java.util.UUID;
* @see SchematicHandler
*/
public SchematicHandler getSchematicHandler() {
return SchematicHandler.manager;
return PlotSquared.platform().getInjector().getInstance(SchematicHandler.class);
}
/**
@ -157,7 +135,7 @@ import java.util.UUID;
if (world == null) {
return Collections.emptySet();
}
return PlotSquared.get().getPlotAreas(world);
return PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world);
}
/**
@ -167,7 +145,8 @@ import java.util.UUID;
* @see MainUtil#sendConsoleMessage(Captions, String...)
*/
public void sendConsoleMessage(String message) {
PlotSquared.log(message);
// TODO: Re-implement
// PlotSquared.log(message);
}
/**

View File

@ -25,20 +25,21 @@
*/
package com.plotsquared.core;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.generator.GeneratorWrapper;
import com.plotsquared.core.generator.HybridUtils;
import com.plotsquared.core.generator.IndependentPlotGenerator;
import com.plotsquared.core.inject.annotations.DefaultGenerator;
import com.plotsquared.core.location.World;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.queue.QueueProvider;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.InventoryUtil;
import com.plotsquared.core.util.PermHandler;
import com.plotsquared.core.util.PlatformWorldManager;
import com.plotsquared.core.util.PlayerManager;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.SetupUtils;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.logger.ILogger;
@ -47,6 +48,8 @@ import com.sk89q.worldedit.extension.platform.Actor;
import net.kyori.adventure.audience.Audience;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.util.List;
@ -57,7 +60,7 @@ import java.util.Map;
*
* @param <P> Player type
*/
public interface IPlotMain<P> extends ILogger {
public interface PlotPlatform<P> extends ILogger {
/**
* Logs a message to console.
@ -93,20 +96,6 @@ public interface IPlotMain<P> extends ILogger {
*/
void shutdown();
/**
* Gets the version of the PlotSquared being used.
*
* @return the plugin version
*/
int[] getPluginVersion();
/**
* Gets the version of the PlotSquared being used as a string.
*
* @return the plugin version as a string
*/
String getPluginVersionString();
default String getPluginName() {
return "PlotSquared";
}
@ -215,6 +204,13 @@ public interface IPlotMain<P> extends ILogger {
*/
HybridUtils initHybridUtils();
/**
* Starts the {@link ChatManager}.
*
* @return the ChatManager
*/
ChatManager initChatManager();
/**
* Start Metrics.
*/
@ -227,12 +223,6 @@ public interface IPlotMain<P> extends ILogger {
*/
void setGenerator(String world);
/**
* Gets the {@link InventoryUtil} class (used for implementation specific
* inventory guis).
*/
InventoryUtil initInventoryUtil();
/**
* Unregisters a {@link PlotPlayer} from cache e.g. if they have logged off.
*
@ -251,49 +241,121 @@ public interface IPlotMain<P> extends ILogger {
GeneratorWrapper<?> wrapPlotGenerator(String world, IndependentPlotGenerator generator);
/**
* Register the chunk processor which will clean out chunks that have too
* many block states or entities.
*/
void registerChunkProcessor();
/**
* Register the world initialization events (used to keep track of worlds
* being generated).
*/
void registerWorldEvents();
/**
* Usually HybridGen
*
* @return Default implementation generator
*/
@NotNull IndependentPlotGenerator getDefaultGenerator();
@Nonnull default IndependentPlotGenerator getDefaultGenerator() {
return getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class));
}
List<Map.Entry<Map.Entry<String, String>, Boolean>> getPluginIds();
Actor getConsole();
/**
* Get the backup manager instance
*
* @return Backup manager
*/
@NotNull BackupManager getBackupManager();
@Nonnull default BackupManager getBackupManager() {
return getInjector().getInstance(BackupManager.class);
}
/**
* Get the platform specific world manager
*
* @return World manager
*/
@NotNull PlatformWorldManager<?> getWorldManager();
@Nonnull default PlatformWorldManager<?> getWorldManager() {
return getInjector().getInstance(PlatformWorldManager.class);
}
/**
* Get the player manager implementation for the platform
*
* @return Player manager
*/
@NotNull PlayerManager<? extends PlotPlayer<P>, ? extends P> getPlayerManager();
@Nonnull default PlayerManager<? extends PlotPlayer<P>, ? extends P> getPlayerManager() {
return getInjector().getInstance(PlayerManager.class);
}
/**
* Get a platform world wrapper from a world name
*
* @param worldName World name
* @return Platform world wrapper
*/
@Nonnull World<?> getPlatformWorld(@Nonnull final String worldName);
/**
* Get the {@link com.google.inject.Injector} instance used by PlotSquared
*
* @return Injector instance
*/
@Nonnull Injector getInjector();
/**
* Get the world utility implementation
*
* @return World utility
*/
@Nonnull default WorldUtil getWorldUtil() {
return getInjector().getInstance(WorldUtil.class);
}
/**
* Get the global block queue implementation
*
* @return Global block queue implementation
*/
@Nonnull default GlobalBlockQueue getGlobalBlockQueue() {
return getInjector().getInstance(GlobalBlockQueue.class);
}
/**
* Get the {@link HybridUtils} implementation for the platform
*
* @return Hybrid utils
*/
@Nonnull default HybridUtils getHybridUtils() {
return getInjector().getInstance(HybridUtils.class);
}
/**
* Get the {@link SetupUtils} implementation for the platform
*
* @return Setup utils
*/
@Nonnull default SetupUtils getSetupUtils() {
return getInjector().getInstance(SetupUtils.class);
}
/**
* Get the {@link EconHandler} implementation for the platform
* *
* @return Econ handler
*/
@Nullable default EconHandler getEconHandler() {
return getInjector().getInstance(EconHandler.class);
}
/**
* Get the {@link RegionManager} implementation for the platform
*
* @return Region manager
*/
@Nonnull default RegionManager getRegionManager() {
return getInjector().getInstance(RegionManager.class);
}
/**
* Get the {@link ChunkManager} implementation for the platform
*
* @return Region manager
*/
@Nonnull default ChunkManager getChunkManager() {
return getInjector().getInstance(ChunkManager.class);
}
/**
* Get the platform specific console {@link Audience}

File diff suppressed because it is too large Load Diff

View File

@ -28,7 +28,7 @@ package com.plotsquared.core.backup;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.Files;

View File

@ -28,8 +28,8 @@ package com.plotsquared.core.backup;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.Objects;
@ -45,8 +45,8 @@ public interface BackupManager {
* @param plot Plot to perform the automatic backup on
* @param whenDone Action that runs when the automatic backup has been completed
*/
static void backup(@Nullable PlotPlayer player, @NotNull final Plot plot, @NotNull Runnable whenDone) {
Objects.requireNonNull(PlotSquared.imp()).getBackupManager().automaticBackup(player, plot, whenDone);
static void backup(@Nullable PlotPlayer player, @Nonnull final Plot plot, @Nonnull Runnable whenDone) {
Objects.requireNonNull(PlotSquared.platform()).getBackupManager().automaticBackup(player, plot, whenDone);
}
/**
@ -56,7 +56,7 @@ public interface BackupManager {
* @param plot Plot to get the backup profile for
* @return Backup profile
*/
@NotNull BackupProfile getProfile(@NotNull final Plot plot);
@Nonnull BackupProfile getProfile(@Nonnull final Plot plot);
/**
* This will perform an automatic backup of the plot iff the plot has an owner,
@ -67,14 +67,14 @@ public interface BackupManager {
* @param plot Plot to perform the automatic backup on
* @param whenDone Action that runs when the automatic backup has been completed
*/
void automaticBackup(@Nullable PlotPlayer player, @NotNull final Plot plot, @NotNull Runnable whenDone);
void automaticBackup(@Nullable PlotPlayer player, @Nonnull final Plot plot, @Nonnull Runnable whenDone);
/**
* Get the directory in which backups are stored
*
* @return Backup directory path
*/
@NotNull Path getBackupPath();
@Nonnull Path getBackupPath();
/**
* Get the maximum amount of backups that may be stored for

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.backup;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.nio.file.Path;
import java.util.List;
@ -38,7 +38,7 @@ public interface BackupProfile {
*
* @return Future that will be completed with available backups
*/
@NotNull CompletableFuture<List<Backup>> listBackups();
@Nonnull CompletableFuture<List<Backup>> listBackups();
/**
* Remove all backups stored for this profile
@ -51,7 +51,7 @@ public interface BackupProfile {
*
* @return Folder that contains the backups for this profile
*/
@NotNull Path getBackupDirectory();
@Nonnull Path getBackupDirectory();
/**
* Create a backup of the plot. If the profile is at the
@ -59,7 +59,7 @@ public interface BackupProfile {
*
* @return Future that completes with the created backup.
*/
@NotNull CompletableFuture<Backup> createBackup();
@Nonnull CompletableFuture<Backup> createBackup();
/**
* Restore a backup
@ -67,6 +67,6 @@ public interface BackupProfile {
* @param backup Backup to restore
* @return Future that completes when the backup has finished
*/
@NotNull CompletableFuture<Void> restoreBackup(@NotNull final Backup backup);
@Nonnull CompletableFuture<Void> restoreBackup(@Nonnull final Backup backup);
}

View File

@ -25,11 +25,12 @@
*/
package com.plotsquared.core.backup;
import com.google.inject.Singleton;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.Objects;
@ -37,19 +38,19 @@ import java.util.Objects;
/**
* {@inheritDoc}
*/
public class NullBackupManager implements BackupManager {
@Singleton public class NullBackupManager implements BackupManager {
@Override @NotNull public BackupProfile getProfile(@NotNull Plot plot) {
@Override @Nonnull public BackupProfile getProfile(@Nonnull Plot plot) {
return new NullBackupProfile();
}
@Override public void automaticBackup(@Nullable PlotPlayer plotPlayer,
@NotNull Plot plot, @NotNull Runnable whenDone) {
@Nonnull Plot plot, @Nonnull Runnable whenDone) {
whenDone.run();
}
@Override @NotNull public Path getBackupPath() {
return Objects.requireNonNull(PlotSquared.imp()).getDirectory().toPath();
@Override @Nonnull public Path getBackupPath() {
return Objects.requireNonNull(PlotSquared.platform()).getDirectory().toPath();
}
@Override public int getBackupLimit() {

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.backup;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.io.File;
import java.nio.file.Path;
@ -39,22 +39,22 @@ import java.util.concurrent.CompletableFuture;
*/
public class NullBackupProfile implements BackupProfile {
@Override @NotNull public CompletableFuture<List<Backup>> listBackups() {
@Override @Nonnull public CompletableFuture<List<Backup>> listBackups() {
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override public void destroy(){
}
@Override @NotNull public Path getBackupDirectory() {
@Override @Nonnull public Path getBackupDirectory() {
return new File(".").toPath();
}
@Override @NotNull public CompletableFuture<Backup> createBackup() {
@Override @Nonnull public CompletableFuture<Backup> createBackup() {
throw new UnsupportedOperationException("Cannot create backup of an unowned plot");
}
@Override @NotNull public CompletableFuture<Void> restoreBackup(@NotNull final Backup backup) {
@Override @Nonnull public CompletableFuture<Void> restoreBackup(@Nonnull final Backup backup) {
return CompletableFuture.completedFuture(null);
}

View File

@ -25,14 +25,15 @@
*/
package com.plotsquared.core.backup;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Files;
@ -51,22 +52,30 @@ import java.util.concurrent.CompletableFuture;
* plot, which is used to store and retrieve plot backups
* {@inheritDoc}
*/
@RequiredArgsConstructor
public class PlayerBackupProfile implements BackupProfile {
private final UUID owner;
private final Plot plot;
private final BackupManager backupManager;
private final SchematicHandler schematicHandler;
@Inject public PlayerBackupProfile(@Assisted @Nonnull final UUID owner, @Assisted @Nonnull final Plot plot,
@Nonnull final BackupManager backupManager, @Nonnull final SchematicHandler schematicHandler) {
this.owner = owner;
this.plot = plot;
this.backupManager = backupManager;
this.schematicHandler = schematicHandler;
}
private volatile List<Backup> backupCache;
private final Object backupLock = new Object();
private static boolean isValidFile(@NotNull final Path path) {
private static boolean isValidFile(@Nonnull final Path path) {
final String name = path.getFileName().toString();
return name.endsWith(".schem") || name.endsWith(".schematic");
}
@Override @NotNull public CompletableFuture<List<Backup>> listBackups() {
@Override @Nonnull public CompletableFuture<List<Backup>> listBackups() {
synchronized (this.backupLock) {
if (this.backupCache != null) {
return CompletableFuture.completedFuture(backupCache);
@ -112,12 +121,12 @@ public class PlayerBackupProfile implements BackupProfile {
});
}
@NotNull public Path getBackupDirectory() {
@Nonnull public Path getBackupDirectory() {
return resolve(resolve(resolve(backupManager.getBackupPath(), Objects.requireNonNull(plot.getArea().toString(), "plot area id")),
Objects.requireNonNull(plot.getId().toDashSeparatedString(), "plot id")), Objects.requireNonNull(owner.toString(), "owner"));
}
private static Path resolve(@NotNull final Path parent, final String child) {
private static Path resolve(@Nonnull final Path parent, final String child) {
Path path = parent;
try {
if (!Files.exists(parent)) {
@ -133,7 +142,7 @@ public class PlayerBackupProfile implements BackupProfile {
return path;
}
@Override @NotNull public CompletableFuture<Backup> createBackup() {
@Override @Nonnull public CompletableFuture<Backup> createBackup() {
final CompletableFuture<Backup> future = new CompletableFuture<>();
this.listBackups().thenAcceptAsync(backups -> {
synchronized (this.backupLock) {
@ -141,7 +150,7 @@ public class PlayerBackupProfile implements BackupProfile {
backups.get(backups.size() - 1).delete();
}
final List<Plot> plots = Collections.singletonList(plot);
final boolean result = SchematicHandler.manager.exportAll(plots, getBackupDirectory().toFile(),
final boolean result = this.schematicHandler.exportAll(plots, getBackupDirectory().toFile(),
"%world%-%id%-" + System.currentTimeMillis(), () ->
future.complete(new Backup(this, System.currentTimeMillis(), null)));
if (!result) {
@ -153,7 +162,7 @@ public class PlayerBackupProfile implements BackupProfile {
return future;
}
@Override @NotNull public CompletableFuture<Void> restoreBackup(@NotNull final Backup backup) {
@Override @Nonnull public CompletableFuture<Void> restoreBackup(@Nonnull final Backup backup) {
final CompletableFuture<Void> future = new CompletableFuture<>();
if (backup.getFile() == null || !Files.exists(backup.getFile())) {
future.completeExceptionally(new IllegalArgumentException("The specific backup does not exist"));
@ -161,14 +170,14 @@ public class PlayerBackupProfile implements BackupProfile {
TaskManager.runTaskAsync(() -> {
Schematic schematic = null;
try {
schematic = SchematicHandler.manager.getSchematic(backup.getFile().toFile());
schematic = this.schematicHandler.getSchematic(backup.getFile().toFile());
} catch (SchematicHandler.UnsupportedFormatException e) {
e.printStackTrace();
}
if (schematic == null) {
future.completeExceptionally(new IllegalArgumentException("The backup is non-existent or not in the correct format"));
} else {
SchematicHandler.manager.paste(schematic, plot, 0, 1, 0, false, new RunnableVal<Boolean>() {
this.schematicHandler.paste(schematic, plot, 0, 1, 0, false, new RunnableVal<Boolean>() {
@Override public void run(Boolean value) {
if (value) {
future.complete(null);

View File

@ -27,17 +27,20 @@ package com.plotsquared.core.backup;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.inject.factory.PlayerBackupProfileFactory;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.task.TaskManager;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.file.Files;
import java.nio.file.Path;
@ -48,16 +51,18 @@ import java.util.concurrent.TimeUnit;
/**
* {@inheritDoc}
*/
@RequiredArgsConstructor public class SimpleBackupManager implements BackupManager {
@RequiredArgsConstructor @Singleton public class SimpleBackupManager implements BackupManager {
@Getter private final Path backupPath;
private final boolean automaticBackup;
@Getter private final int backupLimit;
private final Cache<PlotCacheKey, BackupProfile> backupProfileCache = CacheBuilder.newBuilder()
.expireAfterAccess(3, TimeUnit.MINUTES).build();
private final PlayerBackupProfileFactory playerBackupProfileFactory;
public SimpleBackupManager() throws Exception {
this.backupPath = Objects.requireNonNull(PlotSquared.imp()).getDirectory().toPath().resolve("backups");
@Inject public SimpleBackupManager(@Nonnull final PlayerBackupProfileFactory playerBackupProfileFactory) throws Exception {
this.playerBackupProfileFactory = playerBackupProfileFactory;
this.backupPath = Objects.requireNonNull(PlotSquared.platform()).getDirectory().toPath().resolve("backups");
if (!Files.exists(backupPath)) {
Files.createDirectory(backupPath);
}
@ -65,12 +70,12 @@ import java.util.concurrent.TimeUnit;
this.backupLimit = Settings.Backup.BACKUP_LIMIT;
}
@Override @NotNull public BackupProfile getProfile(@NotNull final Plot plot) {
@Override @Nonnull public BackupProfile getProfile(@Nonnull final Plot plot) {
if (plot.hasOwner() && !plot.isMerged()) {
try {
return backupProfileCache.get(new PlotCacheKey(plot), () -> new PlayerBackupProfile(plot.getOwnerAbs(), plot, this));
return backupProfileCache.get(new PlotCacheKey(plot), () -> this.playerBackupProfileFactory.create(plot.getOwnerAbs(), plot));
} catch (ExecutionException e) {
final BackupProfile profile = new PlayerBackupProfile(plot.getOwnerAbs(), plot, this);
final BackupProfile profile = this.playerBackupProfileFactory.create(plot.getOwnerAbs(), plot);
this.backupProfileCache.put(new PlotCacheKey(plot), profile);
return profile;
}
@ -78,7 +83,7 @@ import java.util.concurrent.TimeUnit;
return new NullBackupProfile();
}
@Override public void automaticBackup(@Nullable PlotPlayer player, @NotNull final Plot plot, @NotNull Runnable whenDone) {
@Override public void automaticBackup(@Nullable PlotPlayer player, @Nonnull final Plot plot, @Nonnull Runnable whenDone) {
final BackupProfile profile;
if (!this.shouldAutomaticallyBackup() || (profile = getProfile(plot)) instanceof NullBackupProfile) {
whenDone.run();

View File

@ -25,17 +25,19 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import net.kyori.adventure.text.minimessage.Template;
import java.util.Collection;
@ -53,8 +55,11 @@ import java.util.concurrent.TimeoutException;
requiredType = RequiredType.PLAYER)
public class Add extends Command {
public Add() {
private final EventDispatcher eventDispatcher;
@Inject public Add(@Nonnull final EventDispatcher eventDispatcher) {
super(MainCommand.getInstance(), true);
this.eventDispatcher = eventDispatcher;
}
@Override
@ -122,7 +127,7 @@ public class Add extends Command {
}
}
plot.addMember(uuid);
PlotSquared.get().getEventDispatcher().callMember(player, plot, uuid, true);
this.eventDispatcher.callMember(player, plot, uuid, true);
player.sendMessage(TranslatableCaption.of("member.member_added"));
}
}, null);

View File

@ -25,14 +25,19 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.ConfigurationUtil;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
import com.plotsquared.core.events.TeleportCause;
import com.plotsquared.core.generator.AugmentedUtils;
import com.plotsquared.core.generator.HybridPlotWorld;
import com.plotsquared.core.inject.factory.HybridPlotWorldFactory;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.ConsolePlayer;
import com.plotsquared.core.player.PlotPlayer;
@ -40,6 +45,8 @@ import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.message.PlotMessage;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
@ -66,11 +73,14 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import net.kyori.adventure.text.minimessage.Template;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@ -84,6 +94,30 @@ import java.util.Set;
confirmation = true)
public class Area extends SubCommand {
private final PlotAreaManager plotAreaManager;
private final YamlConfiguration worldConfiguration;
private final File worldFile;
private final HybridPlotWorldFactory hybridPlotWorldFactory;
private final SetupUtils setupUtils;
private final WorldUtil worldUtil;
private final RegionManager regionManager;
@Inject public Area(@Nonnull final PlotAreaManager plotAreaManager,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@WorldFile @Nonnull final File worldFile,
@Nonnull final HybridPlotWorldFactory hybridPlotWorldFactory,
@Nonnull final SetupUtils setupUtils,
@Nonnull final WorldUtil worldUtil,
@Nonnull final RegionManager regionManager) {
this.plotAreaManager = plotAreaManager;
this.worldConfiguration = worldConfiguration;
this.worldFile = worldFile;
this.hybridPlotWorldFactory = hybridPlotWorldFactory;
this.setupUtils = setupUtils;
this.worldUtil = worldUtil;
this.regionManager = regionManager;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
if (args.length == 0) {
sendUsage(player);
@ -104,7 +138,7 @@ public class Area extends SubCommand {
player.sendMessage(TranslatableCaption.of("single.single_area_needs_name"));
return false;
}
final PlotArea existingArea = PlotSquared.get().getPlotArea(player.getLocation().getWorld(), args[1]);
final PlotArea existingArea = this.plotAreaManager.getPlotArea(player.getLocation().getWorldName(), args[1]);
if (existingArea != null && existingArea.getId().equalsIgnoreCase(args[1])) {
player.sendMessage(TranslatableCaption.of("single.single_area_name_taken"));
return false;
@ -126,7 +160,7 @@ public class Area extends SubCommand {
player.sendMessage(TranslatableCaption.of("single.single_area_not_square"));
return false;
}
if (PlotSquared.get().getPlotAreaManager().getPlotAreas(
if (this.plotAreaManager.getPlotAreas(
Objects.requireNonNull(playerSelectedRegion.getWorld()).getName(), CuboidRegion.makeCuboid(playerSelectedRegion)).length != 0) {
player.sendMessage(TranslatableCaption.of("single.single_area_overlapping"));
}
@ -139,8 +173,8 @@ public class Area extends SubCommand {
BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ()));
// There's only one plot in the area...
final PlotId plotId = new PlotId(1, 1);
final HybridPlotWorld hybridPlotWorld = new HybridPlotWorld(player.getLocation().getWorld(), args[1],
Objects.requireNonNull(PlotSquared.imp()).getDefaultGenerator(), plotId, plotId);
final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory.create(player.getLocation().getWorldName(), args[1],
Objects.requireNonNull(PlotSquared.platform()).getDefaultGenerator(), plotId, plotId);
// Plot size is the same as the region width
hybridPlotWorld.PLOT_WIDTH = hybridPlotWorld.SIZE = (short) selectedRegion.getWidth();
// We use a schematic generator
@ -155,7 +189,7 @@ public class Area extends SubCommand {
hybridPlotWorld.PLOT_HEIGHT = hybridPlotWorld.ROAD_HEIGHT = hybridPlotWorld.WALL_HEIGHT = playerSelectionMin.getBlockY();
// No sign plz
hybridPlotWorld.setAllowSigns(false);
final File parentFile = MainUtil.getFile(PlotSquared.imp().getDirectory(), "schematics" + File.separator +
final File parentFile = MainUtil.getFile(PlotSquared.platform().getDirectory(), "schematics" + File.separator +
"GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator +
hybridPlotWorld.getId());
if (!parentFile.exists() && !parentFile.mkdirs()) {
@ -189,8 +223,8 @@ public class Area extends SubCommand {
// Now the schematic is saved, which is wonderful!
PlotAreaBuilder singleBuilder = PlotAreaBuilder.ofPlotArea(hybridPlotWorld)
.plotManager(PlotSquared.imp().getPluginName())
.generatorName(PlotSquared.imp().getPluginName())
.plotManager(PlotSquared.platform().getPluginName())
.generatorName(PlotSquared.platform().getPluginName())
.maximumId(plotId)
.minimumId(plotId);
Runnable singleRun = () -> {
@ -200,15 +234,13 @@ public class Area extends SubCommand {
final int offsetX = singlePos1.getX();
final int offsetZ = singlePos1.getZ();
if (offsetX != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX);
this.worldConfiguration.set(path + ".road.offset.x", offsetX);
}
if (offsetZ != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.z", offsetZ);
this.worldConfiguration.set(path + ".road.offset.z", offsetZ);
}
final String world = SetupUtils.manager.setupWorld(singleBuilder);
if (WorldUtil.IMP.isWorld(world)) {
final String world = this.setupUtils.setupWorld(singleBuilder);
if (this.worldUtil.isWorld(world)) {
PlotSquared.get().loadWorld(world, null);
player.sendMessage(TranslatableCaption.of("single.single_area_created"));
} else {
@ -278,16 +310,16 @@ public class Area extends SubCommand {
final int offsetX = bx - (area.ROAD_WIDTH == 0 ? 0 : lower);
final int offsetZ = bz - (area.ROAD_WIDTH == 0 ? 0 : lower);
final CuboidRegion region = RegionUtil.createRegion(bx, tx, bz, tz);
Set<PlotArea> areas =
PlotSquared.get().getPlotAreas(area.getWorldName(), region);
final Set<PlotArea> areas = this.plotAreaManager
.getPlotAreasSet(area.getWorldName(), region);
if (!areas.isEmpty()) {
player.sendMessage(TranslatableCaption.of("cluster.cluster_intersection"),
Template.of("cluster", areas.iterator().next().toString()));
return false;
}
PlotAreaBuilder builder = PlotAreaBuilder.ofPlotArea(area)
.plotManager(PlotSquared.imp().getPluginName())
.generatorName(PlotSquared.imp().getPluginName())
.plotManager(PlotSquared.platform().getPluginName())
.generatorName(PlotSquared.platform().getPluginName())
.minimumId(new PlotId(1, 1))
.maximumId(new PlotId(numX, numZ));
final String path =
@ -295,21 +327,19 @@ public class Area extends SubCommand {
+ builder.minimumId() + '-' + builder.maximumId();
Runnable run = () -> {
if (offsetX != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.x", offsetX);
this.worldConfiguration.set(path + ".road.offset.x", offsetX);
}
if (offsetZ != 0) {
PlotSquared.get().worlds
.set(path + ".road.offset.z", offsetZ);
this.worldConfiguration.set(path + ".road.offset.z", offsetZ);
}
final String world = SetupUtils.manager.setupWorld(builder);
if (WorldUtil.IMP.isWorld(world)) {
final String world = this.setupUtils.setupWorld(builder);
if (this.worldUtil.isWorld(world)) {
PlotSquared.get().loadWorld(world, null);
player.sendMessage(TranslatableCaption.of("setup.setup_finished"));
player.teleport(WorldUtil.IMP.getSpawn(world),
player.teleport(this.worldUtil.getSpawn(world),
TeleportCause.COMMAND);
if (area.getTerrain() != PlotAreaTerrainType.ALL) {
RegionManager.largeRegionTask(world, region,
this.regionManager.largeRegionTask(world, region,
new RunnableVal<BlockVector2>() {
@Override public void run(BlockVector2 value) {
AugmentedUtils
@ -340,17 +370,17 @@ public class Area extends SubCommand {
} else {
id = null;
}
PlotAreaBuilder builder = new PlotAreaBuilder();
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder();
builder.worldName(split[0]);
final HybridPlotWorld pa = new HybridPlotWorld(builder.worldName(), id,
PlotSquared.get().IMP.getDefaultGenerator(), null, null);
PlotArea other = PlotSquared.get().getPlotArea(pa.getWorldName(), id);
final HybridPlotWorld pa = this.hybridPlotWorldFactory.create(builder.worldName(),
id, PlotSquared.platform().getDefaultGenerator(), null, null);
PlotArea other = this.plotAreaManager.getPlotArea(pa.getWorldName(), id);
if (other != null && Objects.equals(pa.getId(), other.getId())) {
player.sendMessage(TranslatableCaption.of("setup.setup_world_taken"),
Template.of("value", pa.toString()));
return false;
}
Set<PlotArea> areas = PlotSquared.get().getPlotAreas(pa.getWorldName());
Set<PlotArea> areas = this.plotAreaManager.getPlotAreasSet(pa.getWorldName());
if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next();
pa.setType(area.getType());
@ -420,26 +450,25 @@ public class Area extends SubCommand {
}
}
if (pa.getType() != PlotAreaType.PARTIAL) {
if (WorldUtil.IMP.isWorld(pa.getWorldName())) {
if (this.worldUtil.isWorld(pa.getWorldName())) {
player.sendMessage(TranslatableCaption.of("setup.setup_world_taken"),
Template.of("value", pa.getWorldName()));
return false;
}
Runnable run = () -> {
String path = "worlds." + pa.getWorldName();
if (!PlotSquared.get().worlds.contains(path)) {
PlotSquared.get().worlds.createSection(path);
if (!this.worldConfiguration.contains(path)) {
this.worldConfiguration.createSection(path);
}
ConfigurationSection section =
PlotSquared.get().worlds.getConfigurationSection(path);
ConfigurationSection section = this.worldConfiguration.getConfigurationSection(path);
pa.saveConfiguration(section);
pa.loadConfiguration(section);
builder.plotManager(PlotSquared.imp().getPluginName());
builder.generatorName(PlotSquared.imp().getPluginName());
String world = SetupUtils.manager.setupWorld(builder);
if (WorldUtil.IMP.isWorld(world)) {
builder.plotManager(PlotSquared.platform().getPluginName());
builder.generatorName(PlotSquared.platform().getPluginName());
String world = this.setupUtils.setupWorld(builder);
if (this.worldUtil.isWorld(world)) {
player.sendMessage(TranslatableCaption.of("setup.setup_finished"));
player.teleport(WorldUtil.IMP.getSpawn(world),
player.teleport(this.worldUtil.getSpawn(world),
TeleportCause.COMMAND);
} else {
MainUtil.sendMessage(player,
@ -447,7 +476,7 @@ public class Area extends SubCommand {
.getWorldName());
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
this.worldConfiguration.save(this.worldFile);
} catch (IOException e) {
e.printStackTrace();
}
@ -465,16 +494,16 @@ public class Area extends SubCommand {
+ " create [world[:id]] [<modifier>=<value>]...");
return false;
}
if (WorldUtil.IMP.isWorld(pa.getWorldName())) {
if (!player.getLocation().getWorld().equals(pa.getWorldName())) {
player.teleport(WorldUtil.IMP.getSpawn(pa.getWorldName()),
if (this.worldUtil.isWorld(pa.getWorldName())) {
if (!player.getLocation().getWorldName().equals(pa.getWorldName())) {
player.teleport(this.worldUtil.getSpawn(pa.getWorldName()),
TeleportCause.COMMAND);
}
} else {
builder.terrainType(PlotAreaTerrainType.NONE);
builder.plotAreaType(PlotAreaType.NORMAL);
SetupUtils.manager.setupWorld(builder);
player.teleport(WorldUtil.IMP.getSpawn(pa.getWorldName()),
this.setupUtils.setupWorld(builder);
player.teleport(this.worldUtil.getSpawn(pa.getWorldName()),
TeleportCause.COMMAND);
}
player.setMeta("area_create_area", pa);
@ -497,7 +526,7 @@ public class Area extends SubCommand {
area = player.getApplicablePlotArea();
break;
case 2:
area = PlotSquared.get().getPlotAreaByString(args[1]);
area = this.plotAreaManager.getPlotAreaByString(args[1]);
break;
default:
Captions.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]");
@ -561,7 +590,7 @@ public class Area extends SubCommand {
Captions.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]");
return false;
}
ArrayList<PlotArea> areas = new ArrayList<>(PlotSquared.get().getPlotAreas());
final List<PlotArea> areas = new ArrayList<>(Arrays.asList(this.plotAreaManager.getAllPlotAreas()));
paginate(player, areas, 8, page,
new RunnableVal3<Integer, PlotArea, PlotMessage>() {
@Override public void run(Integer i, PlotArea area, PlotMessage message) {
@ -622,7 +651,7 @@ public class Area extends SubCommand {
"$4Stop the server and delete: " + area.getWorldName() + "/region");
return false;
}
RegionManager.largeRegionTask(area.getWorldName(), area.getRegion(),
this.regionManager.largeRegionTask(area.getWorldName(), area.getRegion(),
new RunnableVal<BlockVector2>() {
@Override public void run(BlockVector2 value) {
AugmentedUtils
@ -646,7 +675,7 @@ public class Area extends SubCommand {
Captions.COMMAND_SYNTAX.send(player, "/plot visit [area]");
return false;
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]);
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[1]);
if (area == null) {
player.sendMessage(TranslatableCaption.of("errors.not_valid_plot_world"),
Template.of("value", args[1]));
@ -654,26 +683,23 @@ public class Area extends SubCommand {
}
Location center;
if (area.getType() != PlotAreaType.PARTIAL) {
center = WorldUtil.IMP.getSpawn(area.getWorldName());
center = this.worldUtil.getSpawn(area.getWorldName());
player.teleport(center, TeleportCause.COMMAND);
} else {
CuboidRegion region = area.getRegion();
center = new Location(area.getWorldName(), region.getMinimumPoint().getX()
center = Location.at(area.getWorldName(), region.getMinimumPoint().getX()
+ (region.getMaximumPoint().getX() - region.getMinimumPoint().getX()) / 2,
0, region.getMinimumPoint().getZ()
+ (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ()) / 2);
WorldUtil.IMP
.getHighestBlock(area.getWorldName(), center.getX(), center.getZ(), y -> {
center.setY(1 + y);
player.teleport(center, TeleportCause.COMMAND);
});
this.worldUtil.getHighestBlock(area.getWorldName(), center.getX(), center.getZ(), y ->
player.teleport(center.withY(1 + y), TeleportCause.COMMAND));
}
return true;
case "delete":
case "remove":
MainUtil.sendMessage(player,
"$1World creation settings may be stored in multiple locations:"
+ "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.imp()
+ "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.platform()
.getPluginName() + " settings.yml"
+ "\n$3 - $2Multiverse worlds.yml (or any world management plugin)"
+ "\n$1Stop the server and delete it from these locations.");

View File

@ -26,6 +26,7 @@
package com.plotsquared.core.command;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions;
@ -41,7 +42,9 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.Expression;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
@ -50,6 +53,8 @@ import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager;
import net.kyori.adventure.text.minimessage.Template;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Set;
@ -63,6 +68,18 @@ import java.util.Set;
usage = "/plot auto [length,width]")
public class Auto extends SubCommand {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public Auto(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
@Deprecated public static PlotId getNextPlotId(PlotId id, int step) {
return id.getNextId(step);
}
@ -139,7 +156,8 @@ public class Auto extends SubCommand {
player.setMeta(Auto.class.getName(), true);
autoClaimFromDatabase(player, area, start, new RunnableVal<Plot>() {
@Override public void run(final Plot plot) {
TaskManager.IMP.sync(new AutoClaimFinishTask(player, plot, area, schematic));
TaskManager.getImplementation().sync(new AutoClaimFinishTask(player, plot, area, schematic,
PlotSquared.get().getEventDispatcher()));
}
});
}
@ -160,10 +178,9 @@ public class Auto extends SubCommand {
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
PlotArea plotarea = player.getApplicablePlotArea();
if (plotarea == null) {
if (EconHandler.getEconHandler() != null) {
for (PlotArea area : PlotSquared.get().getPlotAreaManager().getAllPlotAreas()) {
if (EconHandler.getEconHandler()
.hasPermission(area.getWorldName(), player.getName(), "plots.auto")) {
if (this.econHandler != null) {
for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) {
if (this.econHandler.hasPermission(area.getWorldName(), player.getName(), "plots.auto")) {
if (plotarea != null) {
plotarea = null;
break;
@ -172,8 +189,8 @@ public class Auto extends SubCommand {
}
}
}
if (PlotSquared.get().getPlotAreaManager().getAllPlotAreas().length == 1) {
plotarea = PlotSquared.get().getPlotAreaManager().getAllPlotAreas()[0];
if (this.plotAreaManager.getAllPlotAreas().length == 1) {
plotarea = this.plotAreaManager.getAllPlotAreas()[0];
}
if (plotarea == null) {
player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
@ -216,7 +233,7 @@ public class Auto extends SubCommand {
// return false;
}
}
PlayerAutoPlotEvent event = PlotSquared.get().getEventDispatcher()
PlayerAutoPlotEvent event = this.eventDispatcher
.callAuto(player, plotarea, schematic, size_x, size_z);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Auto claim");
@ -256,18 +273,18 @@ public class Auto extends SubCommand {
return true;
}
}
if (EconHandler.getEconHandler() != null && plotarea.useEconomy()) {
if (this.econHandler != null && plotarea.useEconomy()) {
Expression<Double> costExp = plotarea.getPrices().get("claim");
double cost = costExp.evaluate((double) (Settings.Limit.GLOBAL ?
player.getPlotCount() :
player.getPlotCount(plotarea.getWorldName())));
cost = (size_x * size_z) * cost;
if (cost > 0d) {
if (!force && EconHandler.getEconHandler().getMoney(player) < cost) {
if (!force && this.econHandler.getMoney(player) < cost) {
sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
EconHandler.getEconHandler().withdrawMoney(player, cost);
this.econHandler.withdrawMoney(player, cost);
sendMessage(player, Captions.REMOVED_BALANCE, cost + "");
}
}
@ -297,7 +314,7 @@ public class Auto extends SubCommand {
}
ArrayList<PlotId> plotIds = MainUtil.getPlotSelectionIds(start, end);
final PlotId pos1 = plotIds.get(0);
final PlotAutoMergeEvent mergeEvent = PlotSquared.get().getEventDispatcher()
final PlotAutoMergeEvent mergeEvent = this.eventDispatcher
.callAutoMerge(plotarea.getPlotAbs(pos1), plotIds);
if (!force && mergeEvent.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Auto merge");

View File

@ -25,7 +25,8 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.backup.BackupProfile;
import com.plotsquared.core.backup.NullBackupProfile;
import com.plotsquared.core.backup.PlayerBackupProfile;
@ -35,6 +36,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import java.nio.file.Files;
import java.time.Instant;
@ -60,8 +62,11 @@ import java.util.stream.Stream;
permission = "plots.backup")
public final class Backup extends Command {
public Backup() {
private final BackupManager backupManager;
@Inject public Backup(@Nonnull final BackupManager backupManager) {
super(MainCommand.getInstance(), true);
this.backupManager = backupManager;
}
private static boolean sendMessage(PlotPlayer player, Captions message, Object... args) {
@ -90,8 +95,7 @@ public final class Backup extends Command {
final Plot plot = player.getCurrentPlot();
if (plot != null) {
final BackupProfile backupProfile =
Objects.requireNonNull(PlotSquared.imp()).getBackupManager().getProfile(plot);
final BackupProfile backupProfile = Objects.requireNonNull(this.backupManager.getProfile(plot));
if (backupProfile instanceof PlayerBackupProfile) {
final CompletableFuture<List<com.plotsquared.core.backup.Backup>> backupList =
backupProfile.listBackups();
@ -135,8 +139,7 @@ public final class Backup extends Command {
.hasPermission(player, Captions.PERMISSION_ADMIN_BACKUP_OTHER)) {
sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_ADMIN_BACKUP_OTHER);
} else {
final BackupProfile backupProfile =
Objects.requireNonNull(PlotSquared.imp()).getBackupManager().getProfile(plot);
final BackupProfile backupProfile = Objects.requireNonNull(this.backupManager.getProfile(plot));
if (backupProfile instanceof NullBackupProfile) {
sendMessage(player, Captions.BACKUP_IMPOSSIBLE,
Captions.GENERIC_OTHER.getTranslated());
@ -175,8 +178,7 @@ public final class Backup extends Command {
.hasPermission(player, Captions.PERMISSION_ADMIN_BACKUP_OTHER)) {
sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_ADMIN_BACKUP_OTHER);
} else {
final BackupProfile backupProfile =
Objects.requireNonNull(PlotSquared.imp()).getBackupManager().getProfile(plot);
final BackupProfile backupProfile = Objects.requireNonNull(this.backupManager.getProfile(plot));
if (backupProfile instanceof NullBackupProfile) {
sendMessage(player, Captions.BACKUP_IMPOSSIBLE,
Captions.GENERIC_OTHER.getTranslated());
@ -237,8 +239,7 @@ public final class Backup extends Command {
sendMessage(player, Captions.NOT_A_NUMBER, args[0]);
return;
}
final BackupProfile backupProfile =
Objects.requireNonNull(PlotSquared.imp()).getBackupManager().getProfile(plot);
final BackupProfile backupProfile = Objects.requireNonNull(this.backupManager.getProfile(plot));
if (backupProfile instanceof NullBackupProfile) {
sendMessage(player, Captions.BACKUP_IMPOSSIBLE,
Captions.GENERIC_OTHER.getTranslated());

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.events.PlotFlagRemoveEvent;
@ -34,10 +35,13 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.PriceFlag;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
@ -49,8 +53,14 @@ import java.util.concurrent.CompletableFuture;
requiredType = RequiredType.NONE)
public class Buy extends Command {
public Buy() {
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public Buy(@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
super(MainCommand.getInstance(), true);
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
@Override
@ -58,7 +68,7 @@ public class Buy extends Command {
RunnableVal3<Command, Runnable, Runnable> confirm,
final RunnableVal2<Command, CommandResult> whenDone) {
check(EconHandler.getEconHandler(), Captions.ECON_DISABLED);
check(this.econHandler, Captions.ECON_DISABLED);
final Plot plot;
if (args.length != 0) {
checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage());
@ -82,15 +92,14 @@ public class Buy extends Command {
confirm.run(this, () -> {
Captions.REMOVED_BALANCE.send(player, price);
EconHandler.getEconHandler().depositMoney(PlotSquared.imp().getPlayerManager().getOfflinePlayer(plot.getOwnerAbs()), price);
this.econHandler.depositMoney(PlotSquared.platform().getPlayerManager().getOfflinePlayer(plot.getOwnerAbs()), price);
PlotPlayer owner = PlotSquared.imp().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs());
PlotPlayer owner = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs());
if (owner != null) {
Captions.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price);
}
PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(PriceFlag.class);
PlotFlagRemoveEvent event =
PlotSquared.get().getEventDispatcher().callFlagRemove(plotFlag, plot);
PlotFlagRemoveEvent event = this.eventDispatcher.callFlagRemove(plotFlag, plot);
if (event.getEventResult() != Result.DENY) {
plot.removeFlag(event.getFlag());
}

View File

@ -71,7 +71,7 @@ public class Caps extends SubCommand {
}
private <T extends PlotFlag<Integer, T>> void sendFormatted(final Plot plot,
final PlotPlayer player, final Class<T> capFlag, final int[] countedEntities,
final PlotPlayer<?> player, final Class<T> capFlag, final int[] countedEntities,
final String name, final int type) {
final int current = countedEntities[type];
final int max = plot.getFlag(capFlag);

View File

@ -26,6 +26,7 @@
package com.plotsquared.core.command;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions;
@ -40,10 +41,15 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.Expression;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@CommandDeclaration(command = "claim",
aliases = "c",
@ -54,18 +60,28 @@ import com.plotsquared.core.util.task.TaskManager;
usage = "/plot claim")
public class Claim extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger("P2/" + Claim.class.getSimpleName());
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public Claim(@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
String schematic = null;
if (args.length >= 1) {
schematic = args[0];
}
Location location = player.getLocation();
final Plot plot = location.getPlotAbs();
Plot plot = location.getPlotAbs();
if (plot == null) {
return sendMessage(player, Captions.NOT_IN_PLOT);
}
PlayerClaimPlotEvent event =
PlotSquared.get().getEventDispatcher().callClaim(player, plot, schematic);
final PlayerClaimPlotEvent event = this.eventDispatcher.callClaim(player, plot, schematic);
schematic = event.getSchematic();
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Claim");
@ -74,7 +90,7 @@ public class Claim extends SubCommand {
boolean force = event.getEventResult() == Result.FORCE;
int currentPlots = Settings.Limit.GLOBAL ?
player.getPlotCount() :
player.getPlotCount(location.getWorld());
player.getPlotCount(location.getWorldName());
int grants = 0;
if (currentPlots >= player.getAllowedPlots() && !force) {
if (player.hasPersistentMeta("grantedPlots")) {
@ -105,14 +121,14 @@ public class Claim extends SubCommand {
}
}
}
if ((EconHandler.getEconHandler() != null) && area.useEconomy() && !force) {
if ((this.econHandler != null) && area.useEconomy() && !force) {
Expression<Double> costExr = area.getPrices().get("claim");
double cost = costExr.evaluate((double) currentPlots);
if (cost > 0d) {
if (EconHandler.getEconHandler().getMoney(player) < cost) {
if (this.econHandler.getMoney(player) < cost) {
return sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost);
}
EconHandler.getEconHandler().withdrawMoney(player, cost);
this.econHandler.withdrawMoney(player, cost);
sendMessage(player, Captions.REMOVED_BALANCE, cost + "");
}
}
@ -130,15 +146,15 @@ public class Claim extends SubCommand {
}
plot.setOwnerAbs(player.getUUID());
final String finalSchematic = schematic;
DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal<Object>() {
DBFunc.createPlotSafe(plot, () -> TaskManager.getImplementation().sync(new RunnableVal<Object>() {
@Override public void run(Object value) {
if (!plot.claim(player, true, finalSchematic, false)) {
PlotSquared.get().getLogger().log(Captions.PREFIX.getTranslated() + String
logger.info(Captions.PREFIX.getTranslated() + String
.format("Failed to claim plot %s", plot.getId().toCommaSeparatedString()));
sendMessage(player, Captions.PLOT_NOT_CLAIMED);
plot.setOwnerAbs(null);
} else if (area.isAutoMerge()) {
PlotMergeEvent event = PlotSquared.get().getEventDispatcher()
PlotMergeEvent event = Claim.this.eventDispatcher
.callMerge(plot, Direction.ALL, Integer.MAX_VALUE, player);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Auto merge on claim");
@ -148,7 +164,7 @@ public class Claim extends SubCommand {
}
}
}), () -> {
PlotSquared.get().getLogger().log(Captions.PREFIX.getTranslated() + String
logger.info(Captions.PREFIX.getTranslated() + String
.format("Failed to add plot %s to the database",
plot.getId().toCommaSeparatedString()));
sendMessage(player, Captions.PLOT_NOT_CLAIMED);

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -37,10 +37,12 @@ import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.AnalysisFlag;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;
@ -56,11 +58,14 @@ import static com.plotsquared.core.command.SubCommand.sendMessage;
confirmation = true)
public class Clear extends Command {
// Note: To clear a specific plot use /plot <plot> clear
// The syntax also works with any command: /plot <plot> <command>
private final EventDispatcher eventDispatcher;
private final GlobalBlockQueue blockQueue;
public Clear() {
@Inject public Clear(@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final GlobalBlockQueue blockQueue) {
super(MainCommand.getInstance(), true);
this.eventDispatcher = eventDispatcher;
this.blockQueue = blockQueue;
}
@Override
@ -69,8 +74,7 @@ public class Clear extends Command {
RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
checkTrue(args.length == 0, Captions.COMMAND_SYNTAX, getUsage());
final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT);
Result eventResult =
PlotSquared.get().getEventDispatcher().callClear(plot).getEventResult();
Result eventResult = this.eventDispatcher.callClear(plot).getEventResult();
if (eventResult == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Clear");
return CompletableFuture.completedFuture(true);
@ -87,13 +91,13 @@ public class Clear extends Command {
final long start = System.currentTimeMillis();
boolean result = plot.clear(true, false, () -> {
plot.unlink();
GlobalBlockQueue.IMP.addEmptyTask(() -> {
this.blockQueue.addEmptyTask(() -> {
plot.removeRunning();
// If the state changes, then mark it as no longer done
if (DoneFlag.isDone(plot)) {
PlotFlag<?, ?> plotFlag =
plot.getFlagContainer().getFlag(DoneFlag.class);
PlotFlagRemoveEvent event = PlotSquared.get().getEventDispatcher()
PlotFlagRemoveEvent event = this.eventDispatcher
.callFlagRemove(plotFlag, plot);
if (event.getEventResult() != Result.DENY) {
plot.removeFlag(event.getFlag());
@ -102,7 +106,7 @@ public class Clear extends Command {
if (!plot.getFlag(AnalysisFlag.class).isEmpty()) {
PlotFlag<?, ?> plotFlag =
plot.getFlagContainer().getFlag(AnalysisFlag.class);
PlotFlagRemoveEvent event = PlotSquared.get().getEventDispatcher()
PlotFlagRemoveEvent event = this.eventDispatcher
.callFlagRemove(plotFlag, plot);
if (event.getEventResult() != Result.DENY) {
plot.removeFlag(event.getFlag());

View File

@ -39,8 +39,8 @@ import com.plotsquared.core.plot.PlotCluster;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.query.PlotQuery;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@ -117,7 +117,7 @@ public class Cluster extends SubCommand {
}
int currentClusters = Settings.Limit.GLOBAL ?
player.getClusterCount() :
player.getPlotCount(player.getLocation().getWorld());
player.getPlotCount(player.getLocation().getWorldName());
if (currentClusters >= player.getAllowedPlots()) {
return sendMessage(player, Captions.CANT_CLAIM_MORE_CLUSTERS);
}
@ -173,7 +173,7 @@ public class Cluster extends SubCommand {
if (Settings.Limit.GLOBAL) {
current = player.getPlayerClusterCount();
} else {
current = player.getPlayerClusterCount(player.getLocation().getWorld());
current = player.getPlayerClusterCount(player.getLocation().getWorldName());
}
int allowed = Permissions
.hasPermissionRange(player, Captions.PERMISSION_CLUSTER_SIZE,
@ -324,7 +324,7 @@ public class Cluster extends SubCommand {
if (Settings.Limit.GLOBAL) {
current = player.getPlayerClusterCount();
} else {
current = player.getPlayerClusterCount(player.getLocation().getWorld());
current = player.getPlayerClusterCount(player.getLocation().getWorldName());
}
current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y);
int allowed = Permissions.hasPermissionRange(player, Captions.PERMISSION_CLUSTER,
@ -385,7 +385,7 @@ public class Cluster extends SubCommand {
DBFunc.setInvited(cluster, uuid);
final PlotPlayer otherPlayer =
PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid);
PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (otherPlayer != null) {
MainUtil.sendMessage(otherPlayer, Captions.CLUSTER_INVITED,
cluster.getName());
@ -448,13 +448,13 @@ public class Cluster extends SubCommand {
DBFunc.removeInvited(cluster, uuid);
final PlotPlayer player2 =
PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid);
PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (player2 != null) {
MainUtil.sendMessage(player2, Captions.CLUSTER_REMOVED,
cluster.getName());
}
for (Plot plot : new ArrayList<>(PlotSquared.get()
.getPlots(player2.getLocation().getWorld(), uuid))) {
for (final Plot plot : PlotQuery.newQuery().inWorld(player2.getLocation()
.getWorldName()).ownedBy(uuid).asCollection()) {
PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) {
plot.unclaim();
@ -512,8 +512,8 @@ public class Cluster extends SubCommand {
cluster.invited.remove(uuid);
DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED, cluster.getName());
for (Plot plot : new ArrayList<>(
PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) {
for (final Plot plot : PlotQuery.newQuery().inWorld(player.getLocation().getWorldName())
.ownedBy(uuid).asCollection()) {
PlotCluster current = plot.getCluster();
if (current != null && current.equals(cluster)) {
plot.unclaim();

View File

@ -41,7 +41,7 @@ import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import lombok.SneakyThrows;
import net.kyori.adventure.text.minimessage.Template;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -594,7 +594,7 @@ public abstract class Command {
return object;
}
@SneakyThrows protected static void sneakyThrow(@NotNull final Throwable throwable) {
@SneakyThrows protected static void sneakyThrow(@Nonnull final Throwable throwable) {
throw throwable;
}

View File

@ -86,7 +86,7 @@ public class Comment extends SubCommand {
String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " ");
PlotComment comment =
new PlotComment(player.getLocation().getWorld(), plot.getId(), message,
new PlotComment(player.getLocation().getWorldName(), plot.getId(), message,
player.getName(), inbox.toString(), System.currentTimeMillis());
boolean result = inbox.addComment(plot, comment);
if (!result) {
@ -96,7 +96,7 @@ public class Comment extends SubCommand {
return false;
}
for (final PlotPlayer pp : PlotSquared.imp().getPlayerManager().getPlayers()) {
for (final PlotPlayer pp : PlotSquared.platform().getPlayerManager().getPlayers()) {
if (pp.getAttribute("chatspy")) {
MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " "));
}

View File

@ -25,15 +25,17 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
@ -54,13 +56,22 @@ public class Condense extends SubCommand {
public static boolean TASK = false;
private final PlotAreaManager plotAreaManager;
private final WorldUtil worldUtil;
@Inject public Condense(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final WorldUtil worldUtil) {
this.plotAreaManager = plotAreaManager;
this.worldUtil = worldUtil;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
if (args.length != 2 && args.length != 3) {
MainUtil.sendMessage(player, getUsage());
return false;
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.getWorldName())) {
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]);
if (area == null || !this.worldUtil.isWorld(area.getWorldName())) {
MainUtil.sendMessage(player, "INVALID AREA");
return false;
}
@ -80,7 +91,8 @@ public class Condense extends SubCommand {
return false;
}
int radius = Integer.parseInt(args[2]);
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots(area));
final List<Plot> plots = new ArrayList<>(area.getPlots());
// remove non base plots
Iterator<Plot> iterator = plots.iterator();
int maxSize = 0;

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.events.PlotFlagRemoveEvent;
@ -34,8 +34,10 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "continue",
description = "Continue a plot that was previously marked as done",
@ -44,6 +46,12 @@ import com.plotsquared.core.util.Permissions;
requiredType = RequiredType.PLAYER)
public class Continue extends SubCommand {
private final EventDispatcher eventDispatcher;
@Inject public Continue(@Nonnull final EventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
Plot plot = player.getCurrentPlot();
if ((plot == null) || !plot.hasOwner()) {
@ -71,7 +79,7 @@ public class Continue extends SubCommand {
}
PlotFlag<?, ?> plotFlag = plot.getFlagContainer().getFlag(DoneFlag.class);
PlotFlagRemoveEvent event =
PlotSquared.get().getEventDispatcher().callFlagRemove(plotFlag, plot);
this.eventDispatcher.callFlagRemove(plotFlag, plot);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Done flag removal");
return true;

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.generator.HybridPlotWorld;
import com.plotsquared.core.generator.HybridUtils;
@ -32,6 +33,7 @@ import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.MainUtil;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "createroadschematic",
aliases = {"crs"},
@ -42,6 +44,12 @@ import com.plotsquared.core.util.MainUtil;
usage = "/plot createroadschematic")
public class CreateRoadSchematic extends SubCommand {
private final HybridUtils hybridUtils;
@Inject public CreateRoadSchematic(@Nonnull final HybridUtils hybridUtils) {
this.hybridUtils = hybridUtils;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
Location location = player.getLocation();
Plot plot = location.getPlotAbs();
@ -51,7 +59,7 @@ public class CreateRoadSchematic extends SubCommand {
if (!(location.getPlotArea() instanceof HybridPlotWorld)) {
return sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
HybridUtils.manager.setupRoadSchematic(plot);
this.hybridUtils.setupRoadSchematic(plot);
MainUtil.sendMessage(player, Captions.SCHEMATIC_ROAD_CREATED);
return true;
}

View File

@ -25,19 +25,27 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.database.Database;
import com.plotsquared.core.database.MySQL;
import com.plotsquared.core.database.SQLManager;
import com.plotsquared.core.database.SQLite;
import com.plotsquared.core.listener.PlotListener;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.plot.world.SinglePlotArea;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import java.io.File;
import java.sql.SQLException;
@ -56,6 +64,21 @@ import java.util.Map.Entry;
usage = "/plot database [area] <sqlite|mysql|import>")
public class DatabaseCommand extends SubCommand {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final PlotListener plotListener;
private final YamlConfiguration worldConfiguration;
@Inject public DatabaseCommand(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final PlotListener plotListener,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.plotListener = plotListener;
this.worldConfiguration = worldConfiguration;
}
public static void insertPlots(final SQLManager manager, final List<Plot> plots,
final PlotPlayer player) {
TaskManager.runTaskAsync(() -> {
@ -80,12 +103,12 @@ public class DatabaseCommand extends SubCommand {
return false;
}
List<Plot> plots;
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]);
if (area != null) {
plots = PlotSquared.get().sortPlotsByTemp(area.getPlots());
args = Arrays.copyOfRange(args, 1, args.length);
} else {
plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots());
plots = PlotSquared.get().sortPlotsByTemp(PlotQuery.newQuery().allPlots().asList());
}
if (args.length < 1) {
MainUtil.sendMessage(player, getUsage());
@ -102,7 +125,7 @@ public class DatabaseCommand extends SubCommand {
.sendMessage(player, "/plot database import <sqlite file> [prefix]");
return false;
}
File file = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
File file = MainUtil.getFile(PlotSquared.platform().getDirectory(),
args[1].endsWith(".db") ? args[1] : args[1] + ".db");
if (!file.exists()) {
MainUtil.sendMessage(player, "&6Database does not exist: " + file);
@ -110,13 +133,13 @@ public class DatabaseCommand extends SubCommand {
}
MainUtil.sendMessage(player, "&6Starting...");
implementation = new SQLite(file);
SQLManager manager =
new SQLManager(implementation, args.length == 3 ? args[2] : "", true);
SQLManager manager = new SQLManager(implementation, args.length == 3 ? args[2] : "",
this.eventDispatcher, this.plotListener, this.worldConfiguration);
HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<>();
for (Entry<String, HashMap<PlotId, Plot>> entry : map.entrySet()) {
String areaName = entry.getKey();
PlotArea pa = PlotSquared.get().getPlotAreaByString(areaName);
PlotArea pa = this.plotAreaManager.getPlotAreaByString(areaName);
if (pa != null) {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
@ -127,11 +150,11 @@ public class DatabaseCommand extends SubCommand {
PlotId newId = newPlot.getId();
PlotId id = plot.getId();
File worldFile =
new File(PlotSquared.imp().getWorldContainer(),
new File(PlotSquared.platform().getWorldContainer(),
id.toCommaSeparatedString());
if (worldFile.exists()) {
File newFile =
new File(PlotSquared.imp().getWorldContainer(),
new File(PlotSquared.platform().getWorldContainer(),
newId.toCommaSeparatedString());
worldFile.renameTo(newFile);
}
@ -179,14 +202,14 @@ public class DatabaseCommand extends SubCommand {
return MainUtil.sendMessage(player, "/plot database sqlite [file]");
}
File sqliteFile =
MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), args[1] + ".db");
MainUtil.getFile(PlotSquared.platform().getDirectory(), args[1] + ".db");
implementation = new SQLite(sqliteFile);
break;
default:
return MainUtil.sendMessage(player, "/plot database [sqlite/mysql]");
}
try {
SQLManager manager = new SQLManager(implementation, prefix, true);
SQLManager manager = new SQLManager(implementation, prefix, this.eventDispatcher, this.plotListener, this.worldConfiguration);
DatabaseCommand.insertPlots(manager, plots, player);
return true;
} catch (ClassNotFoundException | SQLException e) {

View File

@ -25,17 +25,23 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.entity.EntityCategories;
import com.plotsquared.core.util.entity.EntityCategory;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.TaskManager;
import com.plotsquared.core.uuid.UUIDMapping;
import com.sk89q.worldedit.world.entity.EntityType;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Comparator;
@ -48,6 +54,17 @@ import java.util.Map;
permission = "plots.admin")
public class Debug extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger("P2/" + Debug.class.getSimpleName());
private final PlotAreaManager plotAreaManager;
private final RegionManager regionManager;
@Inject public Debug(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final RegionManager regionManager) {
this.plotAreaManager = plotAreaManager;
this.regionManager = regionManager;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
if (args.length > 0) {
if ("player".equalsIgnoreCase(args[0])) {
@ -61,8 +78,7 @@ public class Debug extends SubCommand {
final long start = System.currentTimeMillis();
MainUtil.sendMessage(player, "Fetching loaded chunks...");
TaskManager.runTaskAsync(() -> MainUtil.sendMessage(player,
"Loaded chunks: " + RegionManager.manager
.getChunkChunks(player.getLocation().getWorld()).size() + "(" + (
"Loaded chunks: " + this.regionManager.getChunkChunks(player.getLocation().getWorldName()).size() + "(" + (
System.currentTimeMillis() - start) + "ms) using thread: " + Thread
.currentThread().getName()));
return true;
@ -79,6 +95,13 @@ public class Debug extends SubCommand {
}
return true;
}
if (args.length > 0 && "logging".equalsIgnoreCase(args[0])) {
logger.info("[P2] Info!");
logger.warn("[P2] Warning!");
logger.error("[P2] Error!", new RuntimeException());
logger.debug("[P2] Debug!");
return true;
}
if (args.length > 0 && "entitytypes".equalsIgnoreCase(args[0])) {
EntityCategories.init();
player.sendMessage(Captions.PREFIX.getTranslated() + "§cEntity Categories: ");
@ -118,8 +141,8 @@ public class Debug extends SubCommand {
information.append(header);
information.append(getSection(section, "PlotArea"));
information.append(
getLine(line, "Plot Worlds", StringMan.join(PlotSquared.get().getPlotAreas(), ", ")));
information.append(getLine(line, "Owned Plots", PlotSquared.get().getPlots().size()));
getLine(line, "Plot Worlds", StringMan.join(this.plotAreaManager.getAllPlotAreas(), ", ")));
information.append(getLine(line, "Owned Plots", PlotQuery.newQuery().allPlots().count()));
information.append(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", Captions.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg"));

View File

@ -26,6 +26,7 @@
package com.plotsquared.core.command;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -44,9 +45,11 @@ import com.plotsquared.core.plot.expiration.PlotAnalysis;
import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.message.PlotMessage;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.SchematicHandler;
@ -58,7 +61,12 @@ import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.world.block.BlockState;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings;
import javax.script.ScriptContext;
@ -81,31 +89,46 @@ import java.util.concurrent.CompletableFuture;
aliases = {"exec", "$"},
category = CommandCategory.DEBUG)
public class DebugExec extends SubCommand {
private static final Logger logger = LoggerFactory.getLogger("P2/" + DebugExec.class.getSimpleName());
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final WorldEdit worldEdit;
private final GlobalBlockQueue blockQueue;
private final SchematicHandler schematicHandler;
private final EconHandler econHandler;
private final ChunkManager chunkManager;
private final WorldUtil worldUtil;
private final SetupUtils setupUtils;
private final HybridUtils hybridUtils;
private ScriptEngine engine;
private Bindings scope;
public DebugExec() {
@Inject public DebugExec(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nullable final WorldEdit worldEdit,
@Nonnull final GlobalBlockQueue blockQueue,
@Nonnull final SchematicHandler schematicHandler,
@Nullable final EconHandler econHandler,
@Nonnull final ChunkManager chunkManager,
@Nonnull final WorldUtil worldUtil,
@Nonnull final SetupUtils setupUtils,
@Nonnull final HybridUtils hybridUtils) {
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.worldEdit = worldEdit;
this.blockQueue = blockQueue;
this.schematicHandler = schematicHandler;
this.econHandler = econHandler;
this.chunkManager = chunkManager;
this.worldUtil = worldUtil;
this.setupUtils = setupUtils;
this.hybridUtils = hybridUtils;
init();
/*
try {
if (PlotSquared.get() != null) {
File file = new File(PlotSquared.get().IMP.getDirectory(),
Settings.Paths.SCRIPTS + File.separator + "start.js");
if (file.exists()) {
init();
String script = StringMan.join(Files.readLines(new File(new File(
PlotSquared.get().IMP.getDirectory() + File.separator
+ Settings.Paths.SCRIPTS), "start.js"), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
this.scope.put("THIS", this);
this.scope.put("PlotPlayer", ConsolePlayer.getConsole());
this.engine.eval(script, this.scope);
}
}
} catch (IOException | ScriptException ignored) {
ignored.printStackTrace();
}
*/
}
public ScriptEngine getEngine() {
@ -154,22 +177,22 @@ public class DebugExec extends SubCommand {
// Instances
this.scope.put("PS", PlotSquared.get());
this.scope.put("GlobalBlockQueue", GlobalBlockQueue.IMP);
this.scope.put("GlobalBlockQueue", this.blockQueue);
this.scope.put("ExpireManager", ExpireManager.IMP);
if (PlotSquared.get().worldedit != null) {
if (this.worldEdit != null) {
this.scope.put("WEManager", new WEManager());
}
this.scope.put("TaskManager", TaskManager.IMP);
this.scope.put("TaskManager", TaskManager.getImplementation());
this.scope.put("ConsolePlayer", ConsolePlayer.getConsole());
this.scope.put("SchematicHandler", SchematicHandler.manager);
this.scope.put("ChunkManager", ChunkManager.manager);
this.scope.put("BlockManager", WorldUtil.IMP);
this.scope.put("SetupUtils", SetupUtils.manager);
this.scope.put("EventUtil", PlotSquared.get().getEventDispatcher());
this.scope.put("EconHandler", EconHandler.getEconHandler());
this.scope.put("SchematicHandler", this.schematicHandler);
this.scope.put("ChunkManager", this.chunkManager);
this.scope.put("BlockManager", this.worldUtil);
this.scope.put("SetupUtils", this.setupUtils);
this.scope.put("EventUtil", this.eventDispatcher);
this.scope.put("EconHandler", this.econHandler);
this.scope.put("DBFunc", DBFunc.dbManager);
this.scope.put("HybridUtils", HybridUtils.manager);
this.scope.put("IMP", PlotSquared.get().IMP);
this.scope.put("HybridUtils", this.hybridUtils);
this.scope.put("IMP", PlotSquared.platform());
this.scope.put("MainCommand", MainCommand.getInstance());
// enums
@ -200,7 +223,7 @@ public class DebugExec extends SubCommand {
return true;
}
MainUtil.sendMessage(player, "$1Starting task...");
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
this.hybridUtils.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override public void run(PlotAnalysis value) {
MainUtil.sendMessage(player,
"$1Done: $2Use $3/plot debugexec analyze$2 for more information");
@ -245,7 +268,7 @@ public class DebugExec extends SubCommand {
GlobalFlagContainer.getInstance().getFlagFromString(flag);
if (flagInstance != null) {
for (Plot plot : PlotSquared.get().getBasePlots()) {
PlotFlagRemoveEvent event = PlotSquared.get().getEventDispatcher()
PlotFlagRemoveEvent event = this.eventDispatcher
.callFlagRemove(flagInstance, plot);
if (event.getEventResult() != Result.DENY) {
plot.removeFlag(event.getFlag());
@ -259,17 +282,16 @@ public class DebugExec extends SubCommand {
"&cInvalid syntax: /plot debugexec start-rgar <world>");
return false;
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]);
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[1]);
if (area == null) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD, args[1]);
return false;
}
boolean result;
if (HybridUtils.regions != null) {
result = HybridUtils.manager
.scheduleRoadUpdate(area, HybridUtils.regions, 0, new HashSet<>());
result = this.hybridUtils.scheduleRoadUpdate(area, HybridUtils.regions, 0, new HashSet<>());
} else {
result = HybridUtils.manager.scheduleRoadUpdate(area, 0);
result = this.hybridUtils.scheduleRoadUpdate(area, 0);
}
if (!result) {
MainUtil.sendMessage(player,
@ -288,7 +310,7 @@ public class DebugExec extends SubCommand {
return true;
case "start-expire":
if (ExpireManager.IMP == null) {
ExpireManager.IMP = new ExpireManager();
ExpireManager.IMP = new ExpireManager(this.eventDispatcher);
}
if (ExpireManager.IMP.runAutomatedTask()) {
return MainUtil.sendMessage(player, "Started plot expiry task");
@ -306,7 +328,7 @@ public class DebugExec extends SubCommand {
case "addcmd":
try {
final String cmd = StringMan.join(Files.readLines(MainUtil.getFile(new File(
PlotSquared.get().IMP.getDirectory() + File.separator
PlotSquared.platform().getDirectory() + File.separator
+ Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null,
@ -338,7 +360,7 @@ public class DebugExec extends SubCommand {
case "run":
try {
script = StringMan.join(Files.readLines(MainUtil.getFile(new File(
PlotSquared.get().IMP.getDirectory() + File.separator
PlotSquared.platform().getDirectory() + File.separator
+ Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
if (args.length > 2) {
@ -354,7 +376,7 @@ public class DebugExec extends SubCommand {
}
break;
case "list-scripts":
String path = PlotSquared.get().IMP.getDirectory() + File.separator
String path = PlotSquared.platform().getDirectory() + File.separator
+ Settings.Paths.SCRIPTS;
File folder = new File(path);
File[] filesArray = folder.listFiles();
@ -447,7 +469,6 @@ public class DebugExec extends SubCommand {
}
init();
this.scope.put("PlotPlayer", player);
PlotSquared.debug("> " + script);
try {
if (async) {
final String toExec = script;
@ -459,14 +480,12 @@ public class DebugExec extends SubCommand {
} catch (ScriptException e) {
e.printStackTrace();
}
PlotSquared
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
logger.info("[P2] > {}ms -> {}", System.currentTimeMillis() - start, result);
});
} else {
long start = System.currentTimeMillis();
Object result = this.engine.eval(script, this.scope);
PlotSquared
.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
logger.info("[P2] > {}ms -> {}", System.currentTimeMillis() - start, result);
}
return true;
} catch (ScriptException e) {

View File

@ -26,6 +26,7 @@
package com.plotsquared.core.command;
import com.google.common.base.Charsets;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.player.PlotPlayer;
@ -36,6 +37,7 @@ import com.plotsquared.core.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import java.io.File;
import java.util.UUID;
@ -47,8 +49,15 @@ import java.util.concurrent.CompletableFuture;
requiredType = RequiredType.CONSOLE,
category = CommandCategory.TELEPORT)
public class DebugImportWorlds extends Command {
public DebugImportWorlds() {
private final PlotAreaManager plotAreaManager;
private final WorldUtil worldUtil;
@Inject public DebugImportWorlds(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final WorldUtil worldUtil) {
super(MainCommand.getInstance(), true);
this.plotAreaManager = plotAreaManager;
this.worldUtil = worldUtil;
}
@Override
@ -56,14 +65,13 @@ public class DebugImportWorlds extends Command {
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone) throws CommandException {
// UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8))
PlotAreaManager pam = PlotSquared.get().getPlotAreaManager();
if (!(pam instanceof SinglePlotAreaManager)) {
if (!(this.plotAreaManager instanceof SinglePlotAreaManager)) {
player.sendMessage("Must be a single plot area!");
return CompletableFuture.completedFuture(false);
}
SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea();
SinglePlotArea area = ((SinglePlotAreaManager) this.plotAreaManager).getArea();
PlotId id = new PlotId(0, 0);
File container = PlotSquared.imp().getWorldContainer();
File container = PlotSquared.platform().getWorldContainer();
if (container.equals(new File("."))) {
player.sendMessage(
"World container must be configured to be a separate directory to your base files!");
@ -71,7 +79,7 @@ public class DebugImportWorlds extends Command {
}
for (File folder : container.listFiles()) {
String name = folder.getName();
if (!WorldUtil.IMP.isWorld(name) && PlotId.fromStringOrNull(name) == null) {
if (!this.worldUtil.isWorld(name) && PlotId.fromStringOrNull(name) == null) {
UUID uuid;
if (name.length() > 16) {
uuid = UUID.fromString(name);

View File

@ -27,7 +27,10 @@ package com.plotsquared.core.command;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.inject.annotations.ConfigFile;
import com.plotsquared.core.inject.annotations.WorldFile;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.player.PlotPlayer;
@ -35,7 +38,8 @@ import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.PremiumVerification;
import com.plotsquared.core.util.net.IncendoPaster;
import com.plotsquared.core.util.task.TaskManager;
import lombok.NonNull;
import javax.annotation.Nonnull;
import java.io.BufferedReader;
import java.io.File;
@ -59,7 +63,16 @@ import java.util.stream.Collectors;
requiredType = RequiredType.NONE)
public class DebugPaste extends SubCommand {
private static String readFile(@NonNull final File file) throws IOException {
private final File configFile;
private final File worldfile;
@Inject public DebugPaste(@ConfigFile @Nonnull final File configFile,
@WorldFile @Nonnull final File worldFile) {
this.configFile = configFile;
this.worldfile = worldFile;
}
private static String readFile(@Nonnull final File file) throws IOException {
final List<String> lines;
try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
lines = reader.lines().collect(Collectors.toList());
@ -87,13 +100,13 @@ public class DebugPaste extends SubCommand {
b.append("This PlotSquared version is licensed to the spigot user ")
.append(PremiumVerification.getUserID()).append("\n\n");
b.append("# Server Information\n");
b.append("Server Version: ").append(PlotSquared.get().IMP.getServerImplementation())
b.append("Server Version: ").append(PlotSquared.platform().getServerImplementation())
.append("\n");
b.append("online_mode: ").append(!Settings.UUID.OFFLINE).append(';')
.append(!Settings.UUID.OFFLINE).append('\n');
b.append("Plugins:");
for (Map.Entry<Map.Entry<String, String>, Boolean> pluginInfo : PlotSquared
.get().IMP.getPluginIds()) {
.platform().getPluginIds()) {
Map.Entry<String, String> nameVersion = pluginInfo.getKey();
String name = nameVersion.getKey();
String version = nameVersion.getValue();
@ -129,7 +142,7 @@ public class DebugPaste extends SubCommand {
try {
final File logFile =
new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log");
new File(PlotSquared.platform().getDirectory(), "../../logs/latest.log");
if (Files.size(logFile.toPath()) > 14_000_000) {
throw new IOException("Too big...");
}
@ -142,13 +155,13 @@ public class DebugPaste extends SubCommand {
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml",
readFile(PlotSquared.get().configFile)));
readFile(this.configFile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping settings.yml because it's empty");
}
try {
incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml",
readFile(PlotSquared.get().worldsFile)));
readFile(this.worldfile)));
} catch (final IllegalArgumentException ignored) {
MainUtil.sendMessage(player, "&cSkipping worlds.yml because it's empty");
}
@ -161,7 +174,7 @@ public class DebugPaste extends SubCommand {
}
try {
final File MultiverseWorlds = new File(PlotSquared.get().IMP.getDirectory(),
final File MultiverseWorlds = new File(PlotSquared.platform().getDirectory(),
"../Multiverse-Core/worlds.yml");
incendoPaster.addFile(new IncendoPaster.PasteFile("MultiverseCore/worlds.yml",
readFile(MultiverseWorlds)));

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.generator.HybridPlotManager;
import com.plotsquared.core.generator.HybridUtils;
@ -34,6 +35,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.util.MainUtil;
import javax.annotation.Nonnull;
import java.util.Arrays;
@ -44,8 +46,15 @@ import java.util.Arrays;
category = CommandCategory.DEBUG,
permission = "plots.debugroadregen")
public class DebugRoadRegen extends SubCommand {
public static final String USAGE = "/plot debugroadregen <plot|region [height]>";
private final HybridUtils hybridUtils;
@Inject public DebugRoadRegen(@Nonnull final HybridUtils hybridUtils) {
this.hybridUtils = hybridUtils;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
if (args.length < 1) {
MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, DebugRoadRegen.USAGE);
@ -117,7 +126,7 @@ public class DebugRoadRegen extends SubCommand {
MainUtil.sendMessage(player,
"&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic");
MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads");
boolean result = HybridUtils.manager.scheduleSingleRegionRoadUpdate(plot, height);
boolean result = this.hybridUtils.scheduleSingleRegionRoadUpdate(plot, height);
if (!result) {
MainUtil.sendMessage(player,
"&cCannot schedule mass schematic update! (Is one already in progress?)");

View File

@ -25,13 +25,13 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.query.PlotQuery;
import java.util.ArrayList;
import java.util.List;
@CommandDeclaration(command = "debugsavetest",
permission = "plots.debugsavetest",
@ -42,7 +42,7 @@ import java.util.ArrayList;
public class DebugSaveTest extends SubCommand {
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
final List<Plot> plots = PlotQuery.newQuery().allPlots().asList();
MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&6Database sync finished!"));

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.events.Result;
@ -34,10 +34,13 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.Expression;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@CommandDeclaration(command = "delete",
@ -50,9 +53,15 @@ import com.plotsquared.core.util.task.TaskManager;
confirmation = true)
public class Delete extends SubCommand {
// Note: To delete a specific plot use /plot <plot> delete
// The syntax also works with any command: /plot <plot> <command>
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public Delete(@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
Location location = player.getLocation();
final Plot plot = location.getPlotAbs();
@ -62,8 +71,7 @@ public class Delete extends SubCommand {
if (!plot.hasOwner()) {
return !sendMessage(player, Captions.PLOT_UNOWNED);
}
Result eventResult =
PlotSquared.get().getEventDispatcher().callDelete(plot).getEventResult();
Result eventResult = this.eventDispatcher.callDelete(plot).getEventResult();
if (eventResult == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Delete");
return true;
@ -77,7 +85,7 @@ public class Delete extends SubCommand {
final java.util.Set<Plot> plots = plot.getConnectedPlots();
final int currentPlots = Settings.Limit.GLOBAL ?
player.getPlotCount() :
player.getPlotCount(location.getWorld());
player.getPlotCount(location.getWorldName());
Runnable run = () -> {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER);
@ -86,11 +94,11 @@ public class Delete extends SubCommand {
final long start = System.currentTimeMillis();
boolean result = plot.deletePlot(() -> {
plot.removeRunning();
if ((EconHandler.getEconHandler() != null) && plotArea.useEconomy()) {
if ((this.econHandler != null) && plotArea.useEconomy()) {
Expression<Double> valueExr = plotArea.getPrices().get("sell");
double value = plots.size() * valueExr.evaluate((double) currentPlots);
if (value > 0d) {
EconHandler.getEconHandler().depositMoney(player, value);
this.econHandler.depositMoney(player, value);
sendMessage(player, Captions.ADDED_BALANCE, String.valueOf(value));
}
}

View File

@ -25,17 +25,21 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.WorldUtil;
import com.sk89q.worldedit.world.gamemode.GameModes;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
@ -50,8 +54,17 @@ import java.util.concurrent.TimeoutException;
requiredType = RequiredType.PLAYER)
public class Deny extends SubCommand {
public Deny() {
private final PlotAreaManager plotAreaManager;
private final EventDispatcher eventDispatcher;
private final WorldUtil worldUtil;
@Inject public Deny(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final WorldUtil worldUtil) {
super(Argument.PlayerName);
this.plotAreaManager = plotAreaManager;
this.eventDispatcher = eventDispatcher;
this.worldUtil = worldUtil;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
@ -94,9 +107,9 @@ public class Deny extends SubCommand {
plot.removeTrusted(uuid);
}
plot.addDenied(uuid);
PlotSquared.get().getEventDispatcher().callDenied(player, plot, uuid, true);
this.eventDispatcher.callDenied(player, plot, uuid, true);
if (!uuid.equals(DBFunc.EVERYONE)) {
handleKick(PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid), plot);
handleKick(PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid), plot);
} else {
for (PlotPlayer plotPlayer : plot.getPlayersInPlot()) {
// Ignore plot-owners
@ -133,11 +146,10 @@ public class Deny extends SubCommand {
player.stopSpectating();
}
Location location = player.getLocation();
Location spawn = WorldUtil.IMP.getSpawn(location.getWorld());
Location spawn = this.worldUtil.getSpawn(location.getWorldName());
MainUtil.sendMessage(player, Captions.YOU_GOT_DENIED);
if (plot.equals(spawn.getPlot())) {
Location newSpawn =
WorldUtil.IMP.getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]);
Location newSpawn = this.worldUtil.getSpawn(this.plotAreaManager.getAllWorlds()[0]);
if (plot.equals(newSpawn.getPlot())) {
// Kick from server if you can't be teleported to spawn
player.kick(Captions.YOU_GOT_DENIED.getTranslated());

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.events.PlotFlagAddEvent;
import com.plotsquared.core.events.PlotFlagRemoveEvent;
@ -33,7 +33,9 @@ import com.plotsquared.core.events.Result;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.implementations.DescriptionFlag;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "setdescription",
permission = "plots.set.desc",
@ -44,10 +46,15 @@ import com.plotsquared.core.util.MainUtil;
requiredType = RequiredType.PLAYER)
public class Desc extends SetCommand {
private final EventDispatcher eventDispatcher;
@Inject public Desc(@Nonnull final EventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
@Override public boolean set(PlotPlayer player, Plot plot, String desc) {
if (desc.isEmpty()) {
PlotFlagRemoveEvent event = PlotSquared.get().getEventDispatcher()
.callFlagRemove(plot.getFlagContainer().getFlag(DescriptionFlag.class), plot);
PlotFlagRemoveEvent event = this.eventDispatcher.callFlagRemove(plot.getFlagContainer().getFlag(DescriptionFlag.class), plot);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Description removal");
return false;
@ -56,8 +63,7 @@ public class Desc extends SetCommand {
MainUtil.sendMessage(player, Captions.DESC_UNSET);
return true;
}
PlotFlagAddEvent event = PlotSquared.get().getEventDispatcher().callFlagAdd(
plot.getFlagContainer().getFlag(DescriptionFlag.class).createFlagInstance(desc), plot);
PlotFlagAddEvent event = this.eventDispatcher.callFlagAdd(plot.getFlagContainer().getFlag(DescriptionFlag.class).createFlagInstance(desc), plot);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Description set");
return false;

View File

@ -25,7 +25,9 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.player.PlotPlayer;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "dislike",
permission = "plots.dislike",
@ -35,8 +37,14 @@ import com.plotsquared.core.player.PlotPlayer;
requiredType = RequiredType.PLAYER)
public class Dislike extends SubCommand {
private final Like like;
@Inject public Dislike(@Nonnull final Like like) {
this.like = like;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
return Like.handleLike(player, args, false);
return this.like.handleLike(player, args, false);
}
}

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.events.PlotDoneEvent;
@ -39,9 +39,11 @@ import com.plotsquared.core.plot.expiration.ExpireManager;
import com.plotsquared.core.plot.expiration.PlotAnalysis;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.RunnableVal;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "done",
aliases = {"submit"},
@ -51,13 +53,22 @@ import com.plotsquared.core.util.task.RunnableVal;
requiredType = RequiredType.NONE)
public class Done extends SubCommand {
private final EventDispatcher eventDispatcher;
private final HybridUtils hybridUtils;
@Inject public Done(@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final HybridUtils hybridUtils) {
this.eventDispatcher = eventDispatcher;
this.hybridUtils = hybridUtils;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
Location location = player.getLocation();
final Plot plot = location.getPlotAbs();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(player, Captions.NOT_IN_PLOT);
}
PlotDoneEvent event = PlotSquared.get().getEventDispatcher().callDone(plot);
PlotDoneEvent event = this.eventDispatcher.callDone(plot);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Done");
return true;
@ -83,7 +94,7 @@ public class Done extends SubCommand {
finish(plot, player, true);
plot.removeRunning();
} else {
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
this.hybridUtils.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override public void run(PlotAnalysis value) {
plot.removeRunning();
boolean result =

View File

@ -25,12 +25,13 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.SchematicHandler;
@ -38,6 +39,7 @@ import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.task.RunnableVal;
import com.sk89q.jnbt.CompoundTag;
import javax.annotation.Nonnull;
import java.net.URL;
@ -50,9 +52,21 @@ import java.net.URL;
permission = "plots.download")
public class Download extends SubCommand {
private final PlotAreaManager plotAreaManager;
private final SchematicHandler schematicHandler;
private final WorldUtil worldUtil;
@Inject public Download(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final SchematicHandler schematicHandler,
@Nonnull final WorldUtil worldUtil) {
this.plotAreaManager = plotAreaManager;
this.schematicHandler = schematicHandler;
this.worldUtil = worldUtil;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
String world = player.getLocation().getWorld();
if (!PlotSquared.get().hasPlotArea(world)) {
String world = player.getLocation().getWorldName();
if (!this.plotAreaManager.hasPlotArea(world)) {
return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
final Plot plot = player.getCurrentPlot();
@ -84,10 +98,10 @@ public class Download extends SubCommand {
return false;
}
plot.addRunning();
SchematicHandler.manager.getCompoundTag(plot, new RunnableVal<CompoundTag>() {
this.schematicHandler.getCompoundTag(plot, new RunnableVal<CompoundTag>() {
@Override public void run(CompoundTag value) {
plot.removeRunning();
SchematicHandler.manager.upload(value, null, null, new RunnableVal<URL>() {
schematicHandler.upload(value, null, null, new RunnableVal<URL>() {
@Override public void run(URL url) {
if (url == null) {
MainUtil.sendMessage(player, Captions.GENERATING_LINK_FAILED);
@ -106,8 +120,8 @@ public class Download extends SubCommand {
}
MainUtil.sendMessage(player, Captions.MCA_FILE_SIZE);
plot.addRunning();
WorldUtil.IMP.saveWorld(world);
WorldUtil.IMP.upload(plot, null, null, new RunnableVal<URL>() {
this.worldUtil.saveWorld(world);
this.worldUtil.upload(plot, null, null, new RunnableVal<URL>() {
@Override public void run(URL url) {
plot.removeRunning();
if (url == null) {

View File

@ -49,8 +49,8 @@ import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.helpmenu.HelpMenu;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import java.util.ArrayList;
@ -86,7 +86,7 @@ public final class FlagCommand extends Command {
}
private static boolean checkPermValue(@Nonnull final PlotPlayer player,
@NotNull final PlotFlag<?, ?> flag, @NotNull String key, @NotNull String value) {
@Nonnull final PlotFlag<?, ?> flag, @Nonnull String key, @Nonnull String value) {
key = key.toLowerCase();
value = value.toLowerCase();
String perm = CaptionUtility
@ -151,7 +151,7 @@ public final class FlagCommand extends Command {
*
* @return true if the player is allowed to modify the flags at their current location
*/
private static boolean checkRequirements(@NotNull final PlotPlayer player) {
private static boolean checkRequirements(@Nonnull final PlotPlayer player) {
final Location location = player.getLocation();
final Plot plot = location.getPlotAbs();
if (plot == null) {
@ -179,8 +179,8 @@ public final class FlagCommand extends Command {
* @param arg String to extract flag from
* @return The flag, if found, else null
*/
@Nullable private static PlotFlag<?, ?> getFlag(@NotNull final PlotPlayer player,
@NotNull final String arg) {
@Nullable private static PlotFlag<?, ?> getFlag(@Nonnull final PlotPlayer player,
@Nonnull final String arg) {
if (arg != null && arg.length() > 0) {
final PlotFlag<?, ?> flag = GlobalFlagContainer.getInstance().getFlagFromString(arg);
if (flag instanceof InternalFlag || flag == null) {

View File

@ -99,7 +99,7 @@ public class Grant extends Command {
String key = "grantedPlots";
byte[] rawData = Ints.toByteArray(amount);
PlotPlayer online = PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid);
PlotPlayer online = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (online != null) {
online.setPersistentMeta(key, rawData);
} else {

View File

@ -25,13 +25,14 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.events.TeleportCause;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.Permissions;
@ -40,7 +41,7 @@ import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.query.SortingStrategy;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
@ -55,12 +56,16 @@ import java.util.concurrent.CompletableFuture;
requiredType = RequiredType.PLAYER,
category = CommandCategory.TELEPORT)
public class HomeCommand extends Command {
public HomeCommand() {
private final PlotAreaManager plotAreaManager;
@Inject public HomeCommand(@Nonnull final PlotAreaManager plotAreaManager) {
super(MainCommand.getInstance(), true);
this.plotAreaManager = plotAreaManager;
}
private void home(@NotNull final PlotPlayer<?> player,
@NotNull final PlotQuery query, final int page,
private void home(@Nonnull final PlotPlayer<?> player,
@Nonnull final PlotQuery query, final int page,
final RunnableVal3<Command, Runnable, Runnable> confirm,
final RunnableVal2<Command, CommandResult> whenDone) {
List<Plot> plots = query.asList();
@ -82,7 +87,7 @@ public class HomeCommand extends Command {
}), () -> whenDone.run(HomeCommand.this, CommandResult.FAILURE));
}
@NotNull private PlotQuery query(@NotNull final PlotPlayer<?> player) {
@Nonnull private PlotQuery query(@Nonnull final PlotPlayer<?> player) {
// everything plots need to have in common here
return PlotQuery.newQuery().ownedBy(player);
}
@ -134,7 +139,7 @@ public class HomeCommand extends Command {
break;
case 2:
// we assume args[0] is a plot area and args[1] an identifier
PlotArea plotArea = PlotSquared.get().getPlotAreaByString(args[0]);
final PlotArea plotArea = this.plotAreaManager.getPlotAreaByString(args[0]);
identifier = args[1];
if (plotArea == null) {
// invalid command, therefore no plots

View File

@ -25,16 +25,19 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.WorldUtil;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;
@ -52,8 +55,14 @@ import java.util.concurrent.TimeoutException;
requiredType = RequiredType.PLAYER)
public class Kick extends SubCommand {
public Kick() {
private final PlotAreaManager plotAreaManager;
private final WorldUtil worldUtil;
@Inject public Kick(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final WorldUtil worldUtil) {
super(Argument.PlayerName);
this.plotAreaManager = plotAreaManager;
this.worldUtil = worldUtil;
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
@ -86,7 +95,7 @@ public class Kick extends SubCommand {
}
continue;
}
PlotPlayer<?> pp = PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid);
PlotPlayer<?> pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid);
if (pp != null) {
players.add(pp);
}
@ -105,11 +114,10 @@ public class Kick extends SubCommand {
Captions.CANNOT_KICK_PLAYER.send(player, player2.getName());
return;
}
Location spawn = WorldUtil.IMP.getSpawn(location.getWorld());
Location spawn = this.worldUtil.getSpawn(location.getWorldName());
Captions.YOU_GOT_KICKED.send(player2);
if (plot.equals(spawn.getPlot())) {
Location newSpawn = WorldUtil.IMP
.getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]);
Location newSpawn = this.worldUtil.getSpawn(this.plotAreaManager.getAllWorlds()[0]);
if (plot.equals(newSpawn.getPlot())) {
// Kick from server if you can't be teleported to spawn
player2.kick(Captions.YOU_GOT_KICKED.getTranslated());

View File

@ -25,13 +25,15 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@ -43,8 +45,12 @@ import java.util.concurrent.CompletableFuture;
category = CommandCategory.CLAIMING,
requiredType = RequiredType.PLAYER)
public class Leave extends Command {
public Leave() {
private final EventDispatcher eventDispatcher;
@Inject public Leave(@Nonnull final EventDispatcher eventDispatcher) {
super(MainCommand.getInstance(), true);
this.eventDispatcher = eventDispatcher;
}
@Override
@ -62,10 +68,10 @@ public class Leave extends Command {
UUID uuid = player.getUUID();
if (plot.isAdded(uuid)) {
if (plot.removeTrusted(uuid)) {
PlotSquared.get().getEventDispatcher().callTrusted(player, plot, uuid, false);
this.eventDispatcher.callTrusted(player, plot, uuid, false);
}
if (plot.removeMember(uuid)) {
PlotSquared.get().getEventDispatcher().callMember(player, plot, uuid, false);
this.eventDispatcher.callMember(player, plot, uuid, false);
}
MainUtil.sendMessage(player, Captions.PLOT_LEFT, player.getName());
} else {

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -35,9 +36,11 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.Rating;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
@ -53,7 +56,13 @@ import java.util.UUID;
requiredType = RequiredType.PLAYER)
public class Like extends SubCommand {
protected static boolean handleLike(final PlotPlayer player, String[] args,
private final EventDispatcher eventDispatcher;
@Inject public Like(@Nonnull final EventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
protected boolean handleLike(final PlotPlayer<?> player, String[] args,
final boolean like) {
final UUID uuid = player.getUUID();
if (args.length == 1) {
@ -125,7 +134,7 @@ public class Like extends SubCommand {
}
plot.addRating(uuid, new Rating(rating));
final PlotRateEvent event =
PlotSquared.get().getEventDispatcher().callRating(player, plot, new Rating(rating));
this.eventDispatcher.callRating(player, plot, new Rating(rating));
if (event.getRating() != null) {
plot.addRating(uuid, event.getRating());
if (like) {

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.CaptionUtility;
import com.plotsquared.core.configuration.Captions;
@ -37,6 +38,8 @@ import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.expiration.ExpireManager;
import com.plotsquared.core.plot.flag.implementations.DoneFlag;
import com.plotsquared.core.plot.flag.implementations.PriceFlag;
import com.plotsquared.core.plot.message.PlotMessage;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
@ -47,6 +50,8 @@ import com.plotsquared.core.util.TabCompletions;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.query.SortingStrategy;
import com.plotsquared.core.uuid.UUIDMapping;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
@ -69,9 +74,18 @@ import java.util.stream.Collectors;
usage = "/plot list <forsale|mine|shared|world|top|all|unowned|player|world|done|fuzzy <search...>> [#]")
public class ListCmd extends SubCommand {
private final PlotAreaManager plotAreaManager;
private final EconHandler econHandler;
@Inject public ListCmd(@Nonnull final PlotAreaManager plotAreaManager,
@Nullable final EconHandler econHandler) {
this.plotAreaManager = plotAreaManager;
this.econHandler = econHandler;
}
private String[] getArgumentList(PlotPlayer player) {
List<String> args = new ArrayList<>();
if (EconHandler.getEconHandler() != null && Permissions
if (this.econHandler != null && Permissions
.hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) {
args.add("forsale");
}
@ -138,7 +152,7 @@ public class ListCmd extends SubCommand {
page = 0;
}
String world = player.getLocation().getWorld();
String world = player.getLocation().getWorldName();
PlotArea area = player.getApplicablePlotArea();
String arg = args[0].toLowerCase();
final boolean[] sort = new boolean[] {true};
@ -260,7 +274,7 @@ public class ListCmd extends SubCommand {
Templates.of("node", "plots.list.forsale"));
return false;
}
if (EconHandler.getEconHandler() == null) {
if (this.econHandler == null) {
break;
}
plotConsumer.accept(PlotQuery.newQuery().allPlots().thatPasses(plot -> plot.getFlag(PriceFlag.class) > 0));
@ -294,7 +308,7 @@ public class ListCmd extends SubCommand {
plotConsumer.accept(PlotQuery.newQuery().plotsBySearch(term));
break;
default:
if (PlotSquared.get().hasPlotArea(args[0])) {
if (this.plotAreaManager.hasPlotArea(args[0])) {
if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) {
player.sendMessage(TranslatableCaption.of("permission.no_permission"),
Templates.of("node", "plots.list.world"));
@ -378,7 +392,7 @@ public class ListCmd extends SubCommand {
final List<UUIDMapping> names = PlotSquared.get().getImpromptuUUIDPipeline()
.getNames(plot.getOwners()).get(Settings.UUID.BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
for (final UUIDMapping uuidMapping : names) {
PlotPlayer pp = PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuidMapping.getUuid());
PlotPlayer pp = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuidMapping.getUuid());
if (pp != null) {
message = message.text(prefix).color("$4").text(uuidMapping.getUsername()).color("$1")
.tooltip(new PlotMessage("Online").color("$4"));
@ -399,7 +413,7 @@ public class ListCmd extends SubCommand {
@Override public Collection<Command> tab(PlotPlayer player, String[] args, boolean space) {
final List<String> completions = new LinkedList<>();
if (EconHandler.getEconHandler() != null && Permissions
if (this.econHandler != null && Permissions
.hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) {
completions.add("forsale");
}
@ -410,7 +424,7 @@ public class ListCmd extends SubCommand {
completions.add("shared");
}
if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) {
completions.addAll(PlotSquared.imp().getWorldManager().getWorlds());
completions.addAll(PlotSquared.platform().getWorldManager().getWorlds());
}
if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_TOP)) {
completions.add("top");

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.player.PlotPlayer;
@ -33,11 +33,13 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.SchematicHandler;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
import java.net.MalformedURLException;
import java.net.URL;
@ -52,9 +54,18 @@ import java.util.List;
usage = "/plot load")
public class Load extends SubCommand {
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
String world = player.getLocation().getWorld();
if (!PlotSquared.get().hasPlotArea(world)) {
private final PlotAreaManager plotAreaManager;
private final SchematicHandler schematicHandler;
@Inject public Load(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final SchematicHandler schematicHandler) {
this.plotAreaManager = plotAreaManager;
this.schematicHandler = schematicHandler;
}
@Override public boolean onCommand(final PlotPlayer<?> player, final String[] args) {
final String world = player.getLocation().getWorldName();
if (!this.plotAreaManager.hasPlotArea(world)) {
return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
}
final Plot plot = player.getCurrentPlot();
@ -103,7 +114,7 @@ public class Load extends SubCommand {
plot.addRunning();
MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT);
TaskManager.runTaskAsync(() -> {
Schematic taskSchematic = SchematicHandler.manager.getSchematic(url);
Schematic taskSchematic = this.schematicHandler.getSchematic(url);
if (taskSchematic == null) {
plot.removeRunning();
sendMessage(player, Captions.SCHEMATIC_INVALID,
@ -111,8 +122,7 @@ public class Load extends SubCommand {
return;
}
PlotArea area = plot.getArea();
SchematicHandler.manager
.paste(taskSchematic, plot, 0, area.getMinBuildHeight(), 0, false,
this.schematicHandler.paste(taskSchematic, plot, 0, area.getMinBuildHeight(), 0, false,
new RunnableVal<Boolean>() {
@Override public void run(Boolean value) {
plot.removeRunning();
@ -137,7 +147,7 @@ public class Load extends SubCommand {
if (schematics == null) {
plot.addRunning();
TaskManager.runTaskAsync(() -> {
List<String> schematics1 = SchematicHandler.manager.getSaves(player.getUUID());
List<String> schematics1 = this.schematicHandler.getSaves(player.getUUID());
plot.removeRunning();
if ((schematics1 == null) || schematics1.isEmpty()) {
MainUtil.sendMessage(player, Captions.LOAD_FAILED);

View File

@ -25,6 +25,8 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Injector;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.caption.TranslatableCaption;
@ -40,6 +42,8 @@ import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
@ -61,90 +65,95 @@ public class MainCommand extends Command {
public static MainCommand getInstance() {
if (instance == null) {
instance = new MainCommand();
new Caps();
new Buy();
new Save();
new Load();
new Confirm();
new Template();
new Download();
new Template();
new Setup();
new Area();
new DebugSaveTest();
new DebugLoadTest();
new CreateRoadSchematic();
new DebugAllowUnsafe();
new RegenAllRoads();
new Claim();
new Auto();
new HomeCommand();
new Visit();
new Set();
new Clear();
new Delete();
new Trust();
new Add();
new Leave();
new Deny();
new Remove();
new Info();
new Near();
new ListCmd();
new Debug();
new SchematicCmd();
new PluginCmd();
new Purge();
new Reload();
new Relight();
new Merge();
new DebugPaste();
new Unlink();
new Kick();
new Inbox();
new Comment();
new DatabaseCommand();
new Swap();
new Music();
new DebugRoadRegen();
new Trust();
new DebugExec();
new FlagCommand();
new Target();
new Move();
new Condense();
new Copy();
new Chat();
new Trim();
new Done();
new Continue();
new Middle();
new Grant();
// Set commands
new Owner();
new Desc();
new Biome();
new Alias();
new SetHome();
new Cluster();
new DebugImportWorlds();
new Backup();
final Injector injector = PlotSquared.platform().getInjector();
final List<Class<? extends Command>> commands = new LinkedList<>();
commands.add(Caps.class);
commands.add(Buy.class);
commands.add(Save.class);
commands.add(Load.class);
commands.add(Confirm.class);
commands.add(Template.class);
commands.add(Download.class);
commands.add(Setup.class);
commands.add(Area.class);
commands.add(DebugSaveTest.class);
commands.add(DebugLoadTest.class);
commands.add(CreateRoadSchematic.class);
commands.add(DebugAllowUnsafe.class);
commands.add(RegenAllRoads.class);
commands.add(Claim.class);
commands.add(Auto.class);
commands.add(HomeCommand.class);
commands.add(Visit.class);
commands.add(Set.class);
commands.add(Clear.class);
commands.add(Delete.class);
commands.add(Trust.class);
commands.add(Add.class);
commands.add(Leave.class);
commands.add(Deny.class);
commands.add(Remove.class);
commands.add(Info.class);
commands.add(Near.class);
commands.add(ListCmd.class);
commands.add(Debug.class);
commands.add(SchematicCmd.class);
commands.add(PluginCmd.class);
commands.add(Purge.class);
commands.add(Reload.class);
commands.add(Relight.class);
commands.add(Merge.class);
commands.add(DebugPaste.class);
commands.add(Unlink.class);
commands.add(Kick.class);
commands.add(Inbox.class);
commands.add(Comment.class);
commands.add(DatabaseCommand.class);
commands.add(Swap.class);
commands.add(Music.class);
commands.add(DebugRoadRegen.class);
commands.add(DebugExec.class);
commands.add(FlagCommand.class);
commands.add(Target.class);
commands.add(Move.class);
commands.add(Condense.class);
commands.add(Copy.class);
commands.add(Chat.class);
commands.add(Trim.class);
commands.add(Done.class);
commands.add(Continue.class);
commands.add(Middle.class);
commands.add(Grant.class);
commands.add(Owner.class);
commands.add(Desc.class);
commands.add(Biome.class);
commands.add(Alias.class);
commands.add(SetHome.class);
commands.add(Cluster.class);
commands.add(DebugImportWorlds.class);
commands.add(Backup.class);
if (Settings.Ratings.USE_LIKES) {
new Like();
new Dislike();
commands.add(Like.class);
commands.add(Dislike.class);
} else {
new Rate();
commands.add(Rate.class);
}
for (final Class<? extends Command> command : commands) {
injector.getInstance(command);
}
// Referenced commands
instance.toggle = new Toggle();
instance.toggle = injector.getInstance(Toggle.class);
instance.help = new Help(instance);
}
return instance;
}
public static boolean onCommand(final PlotPlayer player, String... args) {
public static boolean onCommand(final PlotPlayer<?> player, String... args) {
final EconHandler econHandler = PlotSquared.platform().getEconHandler();
if (args.length >= 1 && args[0].contains(":")) {
String[] split2 = args[0].split(":");
if (split2.length == 2) {
@ -166,14 +175,14 @@ public class MainCommand extends Command {
public void run(final Command cmd, final Runnable success, final Runnable failure) {
if (cmd.hasConfirmation(player)) {
CmdConfirm.addPending(player, cmd.getUsage(), () -> {
if (EconHandler.getEconHandler() != null) {
if (econHandler != null) {
PlotArea area = player.getApplicablePlotArea();
if (area != null) {
Expression<Double> priceEval =
area.getPrices().get(cmd.getFullId());
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != null
&& EconHandler.getEconHandler().getMoney(player) < price) {
&& econHandler.getMoney(player) < price) {
if (failure != null) {
failure.run();
}
@ -187,12 +196,12 @@ public class MainCommand extends Command {
});
return;
}
if (EconHandler.getEconHandler() != null) {
if (econHandler != null) {
PlotArea area = player.getApplicablePlotArea();
if (area != null) {
Expression<Double> priceEval = area.getPrices().get(cmd.getFullId());
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != 0d && EconHandler.getEconHandler().getMoney(player) < price) {
if (price != 0d && econHandler.getMoney(player) < price) {
if (failure != null) {
failure.run();
}
@ -254,14 +263,14 @@ public class MainCommand extends Command {
if ("f".equals(args[0].substring(1))) {
confirm = new RunnableVal3<Command, Runnable, Runnable>() {
@Override public void run(Command cmd, Runnable success, Runnable failure) {
if (EconHandler.getEconHandler() != null) {
if (PlotSquared.platform().getEconHandler() != null) {
PlotArea area = player.getApplicablePlotArea();
if (area != null) {
Expression<Double> priceEval =
area.getPrices().get(cmd.getFullId());
Double price = priceEval != null ? priceEval.evaluate(0d) : 0d;
if (price != 0d
&& EconHandler.getEconHandler().getMoney(player) < price) {
&& PlotSquared.platform().getEconHandler().getMoney(player) < price) {
if (failure != null) {
failure.run();
}

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -36,10 +37,13 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.Expression;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.StringMan;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
@ -56,6 +60,15 @@ public class Merge extends SubCommand {
public static final String[] values = new String[] {"north", "east", "south", "west"};
public static final String[] aliases = new String[] {"n", "e", "s", "w"};
private final EventDispatcher eventDispatcher;
private final EconHandler econHandler;
@Inject public Merge(@Nonnull final EventDispatcher eventDispatcher,
@Nullable final EconHandler econHandler) {
this.eventDispatcher = eventDispatcher;
this.econHandler = econHandler;
}
public static String direction(float yaw) {
yaw = yaw / 90;
int i = Math.round(yaw);
@ -126,7 +139,7 @@ public class Merge extends SubCommand {
final int size = plot.getConnectedPlots().size();
int max = Permissions.hasPermissionRange(player, "plots.merge", Settings.Limit.MAX_PLOTS);
PlotMergeEvent event =
PlotSquared.get().getEventDispatcher().callMerge(plot, direction, max, player);
this.eventDispatcher.callMerge(plot, direction, max, player);
if (event.getEventResult() == Result.DENY) {
sendMessage(player, Captions.EVENT_DENIED, "Merge");
return false;
@ -156,8 +169,8 @@ public class Merge extends SubCommand {
return true;
}
if (plot.autoMerge(Direction.ALL, maxSize, uuid, terrain)) {
if (EconHandler.getEconHandler() != null && plotArea.useEconomy() && price > 0d) {
EconHandler.getEconHandler().withdrawMoney(player, price);
if (this.econHandler != null && plotArea.useEconomy() && price > 0d) {
this.econHandler.withdrawMoney(player, price);
sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price));
}
MainUtil.sendMessage(player, Captions.SUCCESS_MERGE);
@ -174,8 +187,8 @@ public class Merge extends SubCommand {
uuid = plot.getOwnerAbs();
}
}
if (!force && EconHandler.getEconHandler() != null && plotArea.useEconomy() && price > 0d
&& EconHandler.getEconHandler().getMoney(player) < price) {
if (!force && this.econHandler != null && plotArea.useEconomy() && price > 0d
&& this.econHandler.getMoney(player) < price) {
sendMessage(player, Captions.CANNOT_AFFORD_MERGE, String.valueOf(price));
return false;
}
@ -192,8 +205,8 @@ public class Merge extends SubCommand {
return true;
}
if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) {
if (EconHandler.getEconHandler() != null && plotArea.useEconomy() && price > 0d) {
EconHandler.getEconHandler().withdrawMoney(player, price);
if (this.econHandler != null && plotArea.useEconomy() && price > 0d) {
this.econHandler.withdrawMoney(player, price);
sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price));
}
MainUtil.sendMessage(player, Captions.SUCCESS_MERGE);
@ -212,7 +225,7 @@ public class Merge extends SubCommand {
java.util.Set<UUID> uuids = adjacent.getOwners();
boolean isOnline = false;
for (final UUID owner : uuids) {
final PlotPlayer accepter = PlotSquared.imp().getPlayerManager().getPlayerIfExists(owner);
final PlotPlayer accepter = PlotSquared.platform().getPlayerManager().getPlayerIfExists(owner);
if (!force && accepter == null) {
continue;
}
@ -221,17 +234,17 @@ public class Merge extends SubCommand {
Runnable run = () -> {
MainUtil.sendMessage(accepter, Captions.MERGE_ACCEPTED);
plot.autoMerge(dir, maxSize - size, owner, terrain);
PlotPlayer plotPlayer = PlotSquared.imp().getPlayerManager().getPlayerIfExists(player.getUUID());
PlotPlayer plotPlayer = PlotSquared.platform().getPlayerManager().getPlayerIfExists(player.getUUID());
if (plotPlayer == null) {
sendMessage(accepter, Captions.MERGE_NOT_VALID);
return;
}
if (EconHandler.getEconHandler() != null && plotArea.useEconomy() && price > 0d) {
if (!force && EconHandler.getEconHandler().getMoney(player) < price) {
if (this.econHandler != null && plotArea.useEconomy() && price > 0d) {
if (!force && this.econHandler.getMoney(player) < price) {
sendMessage(player, Captions.CANNOT_AFFORD_MERGE, String.valueOf(price));
return;
}
EconHandler.getEconHandler().withdrawMoney(player, price);
this.econHandler.withdrawMoney(player, price);
sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price));
}
MainUtil.sendMessage(player, Captions.SUCCESS_MERGE);

View File

@ -25,16 +25,18 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.Permissions;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import javax.annotation.Nonnull;
import java.util.concurrent.CompletableFuture;
@ -46,6 +48,12 @@ import java.util.concurrent.CompletableFuture;
requiredType = RequiredType.PLAYER)
public class Move extends SubCommand {
private final PlotAreaManager plotAreaManager;
@Inject public Move(@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@Override
public CompletableFuture<Boolean> execute(PlotPlayer<?> player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
@ -70,7 +78,7 @@ public class Move extends SubCommand {
Captions.COMMAND_SYNTAX.send(player, getUsage());
return CompletableFuture.completedFuture(false);
}
PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]);
PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]);
Plot plot2;
if (area == null) {
plot2 = MainUtil.getPlotFromString(player, args[0], true);

Some files were not shown because too many files have changed in this diff Show More