diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 702f7c2b2..821174878 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -101,9 +101,13 @@ shadowJar { 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") @@ -111,7 +115,7 @@ shadowJar { 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" diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index 994c13ac9..d4848ae84 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -12,6 +12,12 @@ 20200518 compile + + javax.annotation + javax.annotation-api + 1.3.2 + compile + org.bstats bstats-bukkit diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java similarity index 75% rename from Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index e68466d6a..1027ea88d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -25,31 +25,28 @@ */ 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; -import com.plotsquared.bukkit.queue.BukkitLocalQueue; -import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; import com.plotsquared.bukkit.util.BukkitChatManager; -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.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; @@ -59,49 +56,52 @@ 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.ChatManager; -import com.plotsquared.core.util.ChunkManager; 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.WorldUtil; import com.plotsquared.core.util.task.TaskManager; @@ -109,11 +109,8 @@ 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; import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -121,7 +118,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; @@ -132,11 +128,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; @@ -160,12 +156,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 { - - private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitMain.class.getSimpleName()); +@SuppressWarnings("unused") public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform { + 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 { @@ -180,12 +174,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 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 worldManager; + @Override public int[] getServerVersion() { if (this.version == null) { try { @@ -210,11 +214,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 @@ -224,8 +231,14 @@ 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()) { @@ -237,35 +250,154 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< 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); + 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); + 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; @@ -299,63 +431,63 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< // If running Paper we'll also try to use their profiles if (PaperLib.isPaper()) { final PaperUUIDService paperUUIDService = new PaperUUIDService(); - impromptuPipeline.registerService(paperUUIDService); - backgroundPipeline.registerService(paperUUIDService); + 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)); } logger.info("[P2] PlotSquared hooked into PlaceholderAPI"); } else { @@ -364,32 +496,14 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< 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) { - logger.error("[P2] Failed to initialize backup manager", e); - logger.error("[P2] Backup 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(); - } - - logger.info("[P2] Using platform world manager: {}", this.worldManager.getName()); - // Clean up potential memory leak Bukkit.getScheduler().runTaskTimer(this, () -> { try { @@ -416,10 +530,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()) { @@ -483,8 +597,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 uuidQueue = new LinkedBlockingQueue<>(); PlotSquared.get().forEachPlotRaw(plot -> { @@ -556,7 +670,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) { @@ -572,21 +686,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) { @@ -604,13 +704,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() { + @SuppressWarnings("deprecation") private void runEntityTask() { logger.info("[P2] KillAllEntities started"); - TaskManager.runTaskRepeat(() -> PlotSquared.get().forEachPlotArea(plotArea -> { + TaskManager.runTaskRepeat(() -> this.plotAreaManager.forEachPlotArea(plotArea -> { final World world = Bukkit.getWorld(plotArea.getWorldName()); try { if (world == null) { @@ -745,7 +841,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)); } } } @@ -864,13 +960,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; } @@ -878,74 +974,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) { - } - 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) { - } - return null; - } - - @Override public QueueProvider initBlockQueue() { - 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; @@ -956,20 +985,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; @@ -985,7 +1007,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 terrainTypeMap = map.get(plotArea.getType().name().toLowerCase()); terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), @@ -1001,52 +1023,27 @@ 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 (final Exception e) { @@ -1060,16 +1057,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: @@ -1093,11 +1086,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< return BukkitUtil.getPlayer((OfflinePlayer) player); } if (player instanceof String) { - return (PlotPlayer) PlotSquared.imp().getPlayerManager() + return (PlotPlayer) PlotSquared.platform().getPlayerManager() .getPlayerIfExists((String) player); } if (player instanceof UUID) { - return (PlotPlayer) PlotSquared.imp().getPlayerManager() + return (PlotPlayer) PlotSquared.platform().getPlayerManager() .getPlayerIfExists((UUID) player); } return null; @@ -1117,8 +1110,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, Boolean>> getPluginIds() { @@ -1131,16 +1124,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 Player> getPlayerManager() { - return this.playerManager; + @Override public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { + return BukkitWorld.of(worldName); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/EntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/EntityWrapper.java index 6e777f23a..08924e27a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/EntityWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/EntityWrapper.java @@ -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(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/TeleportEntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/TeleportEntityWrapper.java index 45613a751..6a37571a3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/TeleportEntityWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/TeleportEntityWrapper.java @@ -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)); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index a89588598..3e3b74938 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index ff158f295..7c08c6871 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -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); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 6f886904f..60bb34b9a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -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 getDefaultPopulators(@NotNull World world) { + @Override @Nonnull public List getDefaultPopulators(@Nonnull World world) { try { if (!this.loaded) { String name = world.getName(); PlotSquared.get().loadWorld(name, this); - Set areas = PlotSquared.get().getPlotAreas(name); + final Set 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; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java index d5086b06d..6452941a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java @@ -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; } }; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BackupModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BackupModule.java new file mode 100644 index 000000000..d97cf5d05 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BackupModule.java @@ -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 . + */ +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); + } + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java new file mode 100644 index 000000000..c6fe99ba7 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -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 . + */ +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)); + } + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/WorldManagerModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/WorldManagerModule.java new file mode 100644 index 000000000..f098192b5 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/WorldManagerModule.java @@ -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 . + */ +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 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(); + } + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java index 39384ad0f..c22df7c54 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java @@ -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,7 @@ 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; @@ -64,12 +67,15 @@ 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"); @@ -91,7 +97,7 @@ public class ChunkListener implements Listener { HashSet 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); @@ -151,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(); } @@ -178,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; } @@ -201,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(); @@ -231,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(); @@ -279,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(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java index 0bf5e75e8..85903eb9a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java @@ -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 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); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PaperListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PaperListener.java index a512189f7..7dfe8fbcb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PaperListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PaperListener.java @@ -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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java index cead38df8..d218beac0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java @@ -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 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 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 recipients = event.getRecipients(); recipients.clear(); Set 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 { @@ -1066,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; } } @@ -1083,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; @@ -1106,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)); } } } @@ -1139,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"); @@ -1179,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()); @@ -1510,7 +1530,7 @@ 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()) { @@ -1564,7 +1584,7 @@ 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()) { @@ -1648,7 +1668,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 blocks = event.getBlocks(); @@ -1711,7 +1731,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; } @@ -1853,7 +1873,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)) { @@ -1919,8 +1939,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(); @@ -1972,7 +1992,7 @@ public class PlayerEvents extends PlotListener implements Listener { 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); @@ -2103,13 +2123,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); @@ -2194,7 +2214,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()); @@ -2221,7 +2241,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)); } } @@ -2397,7 +2417,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) @@ -2464,7 +2484,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)); } } @@ -2718,7 +2738,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 +2768,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(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java index a5a5ff2f8..a5885d733 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java @@ -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(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java index 59e1fb2ec..dbd0e9dba 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java @@ -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)); } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/BukkitWorldManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/BukkitWorldManager.java index 4646868a1..8a8dd891e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/BukkitWorldManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/BukkitWorldManager.java @@ -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 { +@Singleton public class BukkitWorldManager implements PlatformWorldManager { @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); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/HyperverseWorldManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/HyperverseWorldManager.java index 705a30286..9c96d596c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/HyperverseWorldManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/HyperverseWorldManager.java @@ -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 diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java index e8cb4cf1e..105b8c9c0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java @@ -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 diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java index c61b29f37..69a11523f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java @@ -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 ""; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java index 8f46d3636..3aa5d12c3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitOfflinePlayer.java @@ -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(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 643039600..8ee58b2f5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -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.plotsquared.core.util.StringMan; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -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 { private static boolean CHECK_EFFECTIVE = true; + + private final EconHandler econHandler; public final Player player; private boolean offline; private String name; + /** *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

* * @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 { 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 { 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); @@ -140,10 +152,10 @@ public class BukkitPlayer extends PlotPlayer { player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); } - 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 { @@ -155,8 +167,8 @@ public class BukkitPlayer extends PlotPlayer { } @Override public boolean hasPermission(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); } @@ -236,12 +248,12 @@ public class BukkitPlayer extends PlotPlayer { } @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)); } @@ -259,7 +271,7 @@ public class BukkitPlayer extends PlotPlayer { @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())); } @@ -267,7 +279,7 @@ public class BukkitPlayer extends PlotPlayer { 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); @@ -282,7 +294,7 @@ public class BukkitPlayer extends PlotPlayer { } } - @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; @@ -297,7 +309,7 @@ public class BukkitPlayer extends PlotPlayer { } @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)) { @@ -325,7 +337,7 @@ public class BukkitPlayer extends PlotPlayer { 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()) @@ -355,7 +367,7 @@ public class BukkitPlayer extends PlotPlayer { } - public PlayerTeleportEvent.TeleportCause getTeleportCause(@NotNull final TeleportCause cause) { + public PlayerTeleportEvent.TeleportCause getTeleportCause(@Nonnull final TeleportCause cause) { switch (cause) { case COMMAND: return PlayerTeleportEvent.TeleportCause.COMMAND; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java index a15718a5f..7238709e3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayerManager.java @@ -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 { +@Singleton public class BukkitPlayerManager extends PlayerManager { - @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 { 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)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java index b5197ce23..fa6ccd69d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java @@ -40,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; @@ -49,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; @@ -195,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)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index c20815e1e..3a18ec355 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -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() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java index 27ce9139f..e2e22ed3c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java @@ -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) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 093682cba..325d47544 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -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++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index e71c48158..c7356c13b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -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; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java index 00adeb892..ea16fa873 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -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; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java index fee00a66d..8987e3527 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitPermHandler.java @@ -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; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 44ea03995..55dc45512 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -25,14 +25,16 @@ */ 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; 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; @@ -58,6 +60,7 @@ 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; @@ -75,10 +78,14 @@ 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() && z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); @@ -95,7 +102,7 @@ public class BukkitRegionManager extends RegionManager { final Semaphore semaphore = new Semaphore(1); try { 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); @@ -199,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() { @Override public void run(int[] value) { int bx = value[2]; @@ -237,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); @@ -249,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(); @@ -285,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())); @@ -402,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 entities = BukkitUtil.getEntities(world); int bx = pos1.getX(); int bz = pos1.getZ(); @@ -429,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(); @@ -446,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); @@ -457,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() { @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]); }); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java index 53185b608..e4cc3d071 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -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) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java index b797708f2..c5928c261 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java @@ -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; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index c72d40b0e..f25fdc621 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -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; @@ -37,6 +39,7 @@ import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MainUtil; 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; @@ -51,7 +54,7 @@ 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 org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; @@ -93,8 +96,8 @@ 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; @@ -110,7 +113,7 @@ 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()); @@ -120,20 +123,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 getPlayer(@NonNull final OfflinePlayer op) { + public static PlotPlayer 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()); } /** @@ -271,39 +279,39 @@ public class BukkitUtil extends WorldUtil { MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption); } - 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 getEntities(@NonNull final String worldName) { + public static List getEntities(@Nonnull final String worldName) { World world = getWorld(worldName); if (world != null) { return world.getEntities(); @@ -312,21 +320,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()); } @@ -338,7 +346,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; } @@ -352,7 +360,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); @@ -402,7 +410,7 @@ public class BukkitUtil extends WorldUtil { } @Override - public void getSign(@NonNull final Location location, final Consumer result) { + public void getSign(@Nonnull final Location location, final Consumer result) { ensureLoaded(location, chunk -> { final Block block = chunk.getWorld().getBlockAt(getLocation(location)); if (block.getState() instanceof Sign) { @@ -412,10 +420,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() { + return TaskManager.getImplementation().sync(new RunnableVal() { @Override public void run(String[] value) { if (block.getState() instanceof Sign) { Sign sign = (Sign) block.getState(); @@ -425,20 +433,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(); @@ -446,8 +454,8 @@ public class BukkitUtil extends WorldUtil { } @Override @SuppressWarnings("deprecation") - public void setSign(@NonNull final String worldName, final int x, final int y, final int z, - @NonNull final String[] lines) { + public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, + @Nonnull final String[] lines) { ensureLoaded(worldName, x, z, chunk -> { final World world = getWorld(worldName); final Block block = world.getBlockAt(x, y, z); @@ -462,7 +470,7 @@ public class BukkitUtil extends WorldUtil { } else if (world.getBlockAt(x, y, z - 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); @@ -485,11 +493,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) { @@ -504,8 +512,8 @@ 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) { logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException()); @@ -527,16 +535,16 @@ public class BukkitUtil extends WorldUtil { } @Override - public void getBlock(@NonNull final Location location, final Consumer result) { + public void getBlock(@Nonnull final Location location, final Consumer 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(); } @@ -691,7 +699,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)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java new file mode 100644 index 000000000..70e664c64 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java @@ -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 . + */ +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 { + + private static final Map 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(); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java index bd77fe27d..1f6b7e5cb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java @@ -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)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/UpdateUtility.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/UpdateUtility.java index 88594abd5..45fc4f2fb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/UpdateUtility.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/UpdateUtility.java @@ -28,6 +28,7 @@ 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.Settings; @@ -54,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(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/BungeePermsUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/BungeePermsUUIDService.java index 4de1bdb92..5163b4045 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/BungeePermsUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/BungeePermsUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { final List 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 getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List mappings = new ArrayList<>(usernames.size()); final UUIDPlayerDB uuiddb = BungeePerms.getInstance().getPermissionsManager().getUUIDPlayerDB(); for (final String username : usernames) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/EssentialsUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/EssentialsUUIDService.java index eb473d67e..a2472bd69 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/EssentialsUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/EssentialsUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { return Collections.emptyList(); } - @Override @NotNull public List getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List mappings = new ArrayList<>(usernames.size()); for (final String username : usernames) { try { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LuckPermsUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LuckPermsUUIDService.java index 47bcc9bb3..d2bcae5a5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LuckPermsUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LuckPermsUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { final List 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 getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List mappings = new ArrayList<>(usernames.size()); final UserManager userManager = this.luckPerms.getUserManager(); for (final String username : usernames) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflinePlayerUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflinePlayerUUIDService.java index 7b904e627..7193f9033 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflinePlayerUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflinePlayerUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List 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 getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List wrappers = new ArrayList<>(usernames.size()); for (final String username : usernames) { if (Settings.UUID.OFFLINE) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/PaperUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/PaperUUIDService.java index 4f370c8b3..19ce31c45 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/PaperUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/PaperUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { final List 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 getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List mappings = new ArrayList<>(usernames.size()); for (final String username : usernames) { final PlayerProfile playerProfile = Bukkit.createProfile(username); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLiteUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLiteUUIDService.java index 16b3abff5..b2f2a8707 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLiteUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLiteUUIDService.java @@ -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 getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { final List 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 getUUIDs(@NotNull List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull List usernames) { final List 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 getAll() { + @Nonnull public List getAll() { final List mappings = new LinkedList<>(); try (final PreparedStatement statement = getConnection().prepareStatement("SELECT * FROM `usercache`")) { try (final ResultSet resultSet = statement.executeQuery()) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SquirrelIdUUIDService.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SquirrelIdUUIDService.java index bb1640d33..3d5f2952a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SquirrelIdUUIDService.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SquirrelIdUUIDService.java @@ -32,7 +32,7 @@ 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; @@ -67,7 +67,7 @@ public class SquirrelIdUUIDService implements UUIDService { this.rateLimiter = RateLimiter.create(rateLimit / 600.0D); } - @Override @NotNull public List getNames(@NotNull final List uuids) { + @Override @Nonnull public List getNames(@Nonnull final List uuids) { final List results = new ArrayList<>(uuids.size()); this.rateLimiter.acquire(uuids.size()); try { @@ -101,7 +101,7 @@ public class SquirrelIdUUIDService implements UUIDService { return results; } - @Override @NotNull public List getUUIDs(@NotNull final List usernames) { + @Override @Nonnull public List getUUIDs(@Nonnull final List usernames) { final List results = new ArrayList<>(usernames.size()); this.rateLimiter.acquire(usernames.size()); try { diff --git a/Bukkit/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml index 41967220c..3cfa79a65 100644 --- a/Bukkit/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: ${name} -main: com.plotsquared.bukkit.BukkitMain +main: com.plotsquared.bukkit.BukkitPlatform api-version: "1.13" version: "${version}" load: STARTUP diff --git a/Core/build.gradle b/Core/build.gradle index 3b3779868..9743bc080 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -16,8 +16,10 @@ 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") + 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") } diff --git a/Core/pom.xml b/Core/pom.xml index f69929bfa..ac6a4ef60 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -12,18 +12,36 @@ 20200518 compile
+ + javax.annotation + javax.annotation-api + 1.3.2 + compile + + + com.google.inject + guice + 4.2.3 + compile + + + com.google.inject.extensions + guice-assistedinject + 4.2.3 + compile + + + com.google.code.findbugs + annotations + 3.0.1 + compile + org.projectlombok lombok 1.18.12 runtime - - org.jetbrains - annotations - 19.0.0 - runtime - com.sk89q.worldedit worldedit-core diff --git a/Core/src/main/java/com/plotsquared/core/api/PlotAPI.java b/Core/src/main/java/com/plotsquared/core/PlotAPI.java similarity index 85% rename from Core/src/main/java/com/plotsquared/core/api/PlotAPI.java rename to Core/src/main/java/com/plotsquared/core/PlotAPI.java index 9dc992c29..9a83aae5e 100644 --- a/Core/src/main/java/com/plotsquared/core/api/PlotAPI.java +++ b/Core/src/main/java/com/plotsquared/core/PlotAPI.java @@ -23,12 +23,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -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 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 getPlayerPlots(PlotPlayer player) { - return PlotSquared.get().getPlots(player); + public Set 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. *
    @@ -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); } /** diff --git a/Core/src/main/java/com/plotsquared/core/IPlotMain.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java similarity index 62% rename from Core/src/main/java/com/plotsquared/core/IPlotMain.java rename to Core/src/main/java/com/plotsquared/core/PlotPlatform.java index a38045acb..9a8ff4211 100644 --- a/Core/src/main/java/com/plotsquared/core/IPlotMain.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -25,28 +25,27 @@ */ 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.ChatManager; 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; -import com.plotsquared.core.util.task.TaskManager; -import com.sk89q.worldedit.extension.platform.Actor; -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 +56,7 @@ import java.util.Map; * * @param

    Player type */ -public interface IPlotMain

    extends ILogger { +public interface PlotPlatform

    extends ILogger { /** * Logs a message to console. @@ -93,20 +92,6 @@ public interface IPlotMain

    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"; } @@ -128,13 +113,6 @@ public interface IPlotMain

    extends ILogger { */ String getNMSPackage(); - /** - * Gets the schematic handler. - * - * @return The {@link SchematicHandler} - */ - SchematicHandler initSchematicHandler(); - /** * Starts the {@link ChatManager}. * @@ -142,86 +120,6 @@ public interface IPlotMain

    extends ILogger { */ ChatManager initChatManager(); - /** - * The task manager will run and manage Minecraft tasks. - * - * @return the PlotSquared task manager - */ - TaskManager getTaskManager(); - - /** - * Run the task that will kill road mobs. - */ - void runEntityTask(); - - /** - * Registerss the implementation specific commands. - */ - void registerCommands(); - - /** - * Register the protection system. - */ - void registerPlayerEvents(); - - /** - * Register force field events. - */ - void registerForceFieldEvents(); - - /** - * Registers the WorldEdit hook. - */ - boolean initWorldEdit(); - - /** - * Gets the economy provider, if there is one - * - * @return the PlotSquared economy manager - */ - @Nullable EconHandler getEconomyHandler(); - - /** - * Gets the permission provider, if there is one - * - * @return the PlotSquared permission manager - */ - @Nullable PermHandler getPermissionHandler(); - - /** - * Gets the {@link QueueProvider} class. - */ - QueueProvider initBlockQueue(); - - /** - * Gets the {@link WorldUtil} class. - */ - WorldUtil initWorldUtil(); - - /** - * Gets the chunk manager. - * - * @return the PlotSquared chunk manager - */ - ChunkManager initChunkManager(); - - /** - * Gets the region manager. - * - * @return the PlotSquared region manager - */ - RegionManager initRegionManager(); - - /** - * Gets the {@link SetupUtils} class. - */ - SetupUtils initSetupUtils(); - - /** - * Gets {@link HybridUtils} class. - */ - HybridUtils initHybridUtils(); - /** * Start Metrics. */ @@ -234,12 +132,6 @@ public interface IPlotMain

    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. * @@ -258,48 +150,120 @@ public interface IPlotMain

    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, 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 P> getPlayerManager(); + @Nonnull default PlayerManager, ? 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); + } } diff --git a/Core/src/main/java/com/plotsquared/core/PlotSquared.java b/Core/src/main/java/com/plotsquared/core/PlotSquared.java index d5618ed0f..9a3220f79 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotSquared.java +++ b/Core/src/main/java/com/plotsquared/core/PlotSquared.java @@ -25,8 +25,6 @@ */ package com.plotsquared.core; -import com.plotsquared.core.command.WE_Anywhere; -import com.plotsquared.core.components.ComponentPresetManager; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationUtil; @@ -44,53 +42,37 @@ import com.plotsquared.core.generator.GeneratorWrapper; import com.plotsquared.core.generator.HybridPlotWorld; import com.plotsquared.core.generator.HybridUtils; import com.plotsquared.core.generator.IndependentPlotGenerator; -import com.plotsquared.core.listener.WESubscriber; +import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; +import com.plotsquared.core.listener.PlotListener; import com.plotsquared.core.location.Location; -import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.BlockBucket; 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.PlotCluster; -import com.plotsquared.core.plot.PlotFilter; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotManager; -import com.plotsquared.core.plot.comment.CommentManager; import com.plotsquared.core.plot.expiration.ExpireManager; import com.plotsquared.core.plot.expiration.ExpiryTask; -import com.plotsquared.core.plot.world.DefaultPlotAreaManager; 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.GlobalBlockQueue; -import com.plotsquared.core.util.ChatManager; -import com.plotsquared.core.util.ChunkManager; -import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.EventDispatcher; -import com.plotsquared.core.util.InventoryUtil; import com.plotsquared.core.util.LegacyConverter; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; 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.query.PlotQuery; import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.uuid.UUIDPipeline; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; import lombok.Getter; -import lombok.NonNull; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -115,33 +97,29 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.concurrent.Executors; import java.util.function.Consumer; -import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * An implementation of the core, with a static getter for easy access. */ -@SuppressWarnings({"unused", "WeakerAccess"}) +@SuppressWarnings({"WeakerAccess"}) public class PlotSquared { private static final Logger logger = LoggerFactory.getLogger("P2/" + PlotSquared.class.getSimpleName()); - private static final Set EMPTY_SET = Collections.unmodifiableSet(Collections.emptySet()); private static PlotSquared instance; + // Implementation - public final IPlotMain IMP; + private final PlotPlatform platform; // Current thread private final Thread thread; // UUID pipelines @@ -150,16 +128,14 @@ public class PlotSquared { @Getter private final UUIDPipeline backgroundUUIDPipeline = new UUIDPipeline(Executors.newSingleThreadExecutor()); // WorldEdit instance - public WorldEdit worldedit; - public File styleFile; - public File configFile; - public File worldsFile; - public File translationFile; - public YamlConfiguration style; - public YamlConfiguration worlds; - public YamlConfiguration storage; + @Getter private WorldEdit worldedit; + @Getter private File configFile; + @Getter private File worldsFile; + public File translationFile; // TODO: REMOVE + public YamlConfiguration style; // TODO: REMOVE + @Getter private YamlConfiguration worldConfiguration; // Temporary hold the plots/clusters before the worlds load - public HashMap> clusters_tmp; + private HashMap> clustersTmp; public HashMap> plots_tmp; private YamlConfiguration config; // Platform / Version / Update URL @@ -167,23 +143,23 @@ public class PlotSquared { // Files and configuration @Getter private File jarFile = null; // This file private File storageFile; - @Getter private PlotAreaManager plotAreaManager; @Getter private EventDispatcher eventDispatcher; + @Getter private PlotListener plotListener; /** * Initialize PlotSquared with the desired Implementation class. * - * @param iPlotMain Implementation of {@link IPlotMain} used + * @param iPlotMain Implementation of {@link PlotPlatform} used * @param platform The platform being used */ - public PlotSquared(final IPlotMain iPlotMain, final String platform) { + public PlotSquared(final PlotPlatform iPlotMain, final String platform) { if (instance != null) { throw new IllegalStateException("Cannot re-initialize the PlotSquared singleton"); } instance = this; this.thread = Thread.currentThread(); - this.IMP = iPlotMain; + this.platform = iPlotMain; Settings.PLATFORM = platform; // @@ -192,7 +168,7 @@ public class PlotSquared { ConfigurationSerialization.registerClass(BlockBucket.class, "BlockBucket"); try { - new ReflectionUtils(this.IMP.getNMSPackage()); + new ReflectionUtils(this.platform.getNMSPackage()); try { URL logurl = PlotSquared.class.getProtectionDomain().getCodeSource().getLocation(); this.jarFile = new File( @@ -200,143 +176,28 @@ public class PlotSquared { .toURI().getPath()); } catch (MalformedURLException | URISyntaxException | SecurityException e) { e.printStackTrace(); - this.jarFile = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared.jar"); + this.jarFile = new File(this.platform.getDirectory().getParentFile(), "PlotSquared.jar"); if (!this.jarFile.exists()) { - this.jarFile = new File(this.IMP.getDirectory().getParentFile(), + this.jarFile = new File(this.platform.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); } } - TaskManager.IMP = this.IMP.getTaskManager(); - - // World Util. Has to be done before config files are loaded - WorldUtil.IMP = this.IMP.initWorldUtil(); if (!setupConfigs()) { return; } - this.translationFile = MainUtil.getFile(this.IMP.getDirectory(), - Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + + this.translationFile = MainUtil.getFile(this.platform.getDirectory(), + Settings.Paths.TRANSLATIONS + File.separator + this.platform.getPluginName() + ".use_THIS.yml"); Captions.load(this.translationFile); - // Setup plotAreaManager - if (Settings.Enabled_Components.WORLDS) { - this.plotAreaManager = new SinglePlotAreaManager(); - } else { - this.plotAreaManager = new DefaultPlotAreaManager(); - } + this.worldedit = WorldEdit.getInstance(); - // Database - if (Settings.Enabled_Components.DATABASE) { - setupDatabase(); - } - - // Check if we need to convert old flag values, etc - if (!getConfigurationVersion().equalsIgnoreCase("v5")) { - // Perform upgrade - if (DBFunc.dbManager.convertFlags()) { - logger.info("[P2] Flags were converted successfully"); - // Update the config version - setConfigurationVersion("v5"); - } - } - - // Comments - CommentManager.registerDefaultInboxes(); - // Kill entities - if (Settings.Enabled_Components.KILL_ROAD_MOBS - || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - this.IMP.runEntityTask(); - } - if (Settings.Enabled_Components.EVENTS) { - this.IMP.registerPlayerEvents(); - } - // Required - this.IMP.registerWorldEvents(); - if (Settings.Enabled_Components.CHUNK_PROCESSOR) { - this.IMP.registerChunkProcessor(); - } - startExpiryTasks(); // Create Event utility class - eventDispatcher = new EventDispatcher(); - // create Hybrid utility class - HybridUtils.manager = this.IMP.initHybridUtils(); - // Inventory utility class - InventoryUtil.manager = this.IMP.initInventoryUtil(); - // create setup util class - SetupUtils.manager = this.IMP.initSetupUtils(); - // Set block - GlobalBlockQueue.IMP = - new GlobalBlockQueue(IMP.initBlockQueue(), 1, Settings.QUEUE.TARGET_TIME); - GlobalBlockQueue.IMP.runTask(); - // Set chunk - ChunkManager.manager = this.IMP.initChunkManager(); - RegionManager.manager = this.IMP.initRegionManager(); - // Schematic handler - SchematicHandler.manager = this.IMP.initSchematicHandler(); - // Chat - ChatManager.manager = this.IMP.initChatManager(); - // Commands - if (Settings.Enabled_Components.COMMANDS) { - this.IMP.registerCommands(); - } - // WorldEdit - if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { - try { - if (this.IMP.initWorldEdit()) { - logger.info("[P2] {} hooked into WorldEdit", imp().getPluginName()); - this.worldedit = WorldEdit.getInstance(); - WorldEdit.getInstance().getEventBus().register(new WESubscriber()); - 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"); - - } - } - // Economy - if (Settings.Enabled_Components.ECONOMY) { - TaskManager.runTask(() -> EconHandler.initializeEconHandler()); - } - - if (Settings.Enabled_Components.COMPONENT_PRESETS) { - try { - new ComponentPresetManager(); - } catch (final Exception e) { - logger.error("[P2] Failed to initialize the preset system", e); - } - } - - // World generators: - final ConfigurationSection section = this.worlds.getConfigurationSection("worlds"); - if (section != null) { - for (String world : section.getKeys(false)) { - if (world.equals("CheckingPlotSquaredGenerator")) { - continue; - } - if (WorldUtil.IMP.isWorld(world)) { - this.IMP.setGenerator(world); - } - } - TaskManager.runTaskLater(() -> { - for (String world : section.getKeys(false)) { - if (world.equals("CheckingPlotSquaredGenerator")) { - continue; - } - if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { - logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly", - world, imp().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."); - PlotSquared.this.IMP.setGenerator(world); - } - } - }, 1); - } + this.eventDispatcher = new EventDispatcher(this.worldedit); + // Create plot listener + this.plotListener = new PlotListener(this.eventDispatcher); // Copy files copyFile("addplots.js", Settings.Paths.SCRIPTS); @@ -361,7 +222,15 @@ public class PlotSquared { } catch (Throwable e) { e.printStackTrace(); } + } + /** + * Get the platform specific {@link PlotAreaManager} instance + * + * @return Plot area manager + */ + @Nonnull public PlotAreaManager getPlotAreaManager() { + return this.platform.getInjector().getInstance(PlotAreaManager.class); } /** @@ -373,19 +242,24 @@ public class PlotSquared { return PlotSquared.instance; } - @NotNull public static IPlotMain imp() { - if (instance != null && instance.IMP != null) { - return instance.IMP; + /** + * Get the platform specific implementation of PlotSquared + * + * @return Platform implementation + */ + @Nonnull public static PlotPlatform platform() { + if (instance != null && instance.platform != null) { + return instance.platform; } - throw new IllegalStateException("Plot main implementation is missing"); + throw new IllegalStateException("Plot platform implementation is missing"); } - private void startExpiryTasks() { + public void startExpiryTasks() { if (Settings.Enabled_Components.PLOT_EXPIRY) { - ExpireManager.IMP = new ExpireManager(); + ExpireManager.IMP = new ExpireManager(this.eventDispatcher); ExpireManager.IMP.runAutomatedTask(); for (Settings.Auto_Clear settings : Settings.AUTO_CLEAR.getInstances()) { - ExpiryTask task = new ExpiryTask(settings); + ExpiryTask task = new ExpiryTask(settings, this.getPlotAreaManager()); ExpireManager.IMP.addTask(task); } } @@ -427,15 +301,6 @@ public class PlotSquared { return Settings.PLATFORM; } - public PlotManager getPlotManager(Plot plot) { - return plot.getArea().getPlotManager(); - } - - public PlotManager getPlotManager(Location location) { - PlotArea pa = getPlotAreaAbs(location); - return pa != null ? pa.getPlotManager() : null; - } - /** * Add a global reference to a plot world. * @@ -465,10 +330,10 @@ public class PlotSquared { } } Set clusters; - if (clusters_tmp == null || (clusters = clusters_tmp.remove(plotArea.toString())) == null) { + if (clustersTmp == null || (clusters = clustersTmp.remove(plotArea.toString())) == null) { if (plotArea.getType() == PlotAreaType.PARTIAL) { - clusters = this.clusters_tmp != null ? - this.clusters_tmp.get(plotArea.getWorldName()) : + clusters = this.clustersTmp != null ? + this.clustersTmp.get(plotArea.getWorldName()) : null; if (clusters != null) { Iterator iterator = clusters.iterator(); @@ -486,13 +351,13 @@ public class PlotSquared { cluster.setArea(plotArea); } } - plotAreaManager.addPlotArea(plotArea); + getPlotAreaManager().addPlotArea(plotArea); plotArea.setupBorder(); if (!Settings.Enabled_Components.PERSISTENT_ROAD_REGEN) { return; } File file = new File( - this.IMP.getDirectory() + File.separator + "persistent_regen_data_" + plotArea.getId() + this.platform.getDirectory() + File.separator + "persistent_regen_data_" + plotArea.getId() + "_" + plotArea.getWorldName()); if (!file.exists()) { return; @@ -511,7 +376,7 @@ public class PlotSquared { logger.info("[P2] - Regions: {}", regions.size()); logger.info("[P2] - Chunks: {}", chunks.size()); HybridUtils.UPDATE = true; - HybridUtils.manager.scheduleRoadUpdate(plotArea, regions, height, chunks); + PlotSquared.platform().getHybridUtils().scheduleRoadUpdate(plotArea, regions, height, chunks); } catch (IOException | ClassNotFoundException e) { logger.error("[P2] Error restarting road regeneration", e); } finally { @@ -528,12 +393,12 @@ public class PlotSquared { * @param area the {@code PlotArea} to remove */ public void removePlotArea(PlotArea area) { - plotAreaManager.removePlotArea(area); + getPlotAreaManager().removePlotArea(area); setPlotsTmp(area); } - public void removePlotAreas(String world) { - for (PlotArea area : getPlotAreas(world)) { + public void removePlotAreas(@Nonnull final String world) { + for (final PlotArea area : this.getPlotAreaManager().getPlotAreasSet(world)) { if (area.getWorldName().equals(world)) { removePlotArea(area); } @@ -549,15 +414,15 @@ public class PlotSquared { for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } - if (this.clusters_tmp == null) { - this.clusters_tmp = new HashMap<>(); + if (this.clustersTmp == null) { + this.clustersTmp = new HashMap<>(); } - this.clusters_tmp.put(area.toString(), area.getClusters()); + this.clustersTmp.put(area.toString(), area.getClusters()); } - public Set getClusters(String world) { - Set set = new HashSet<>(); - for (PlotArea area : getPlotAreas(world)) { + public Set getClusters(@Nonnull final String world) { + final Set set = new HashSet<>(); + for (final PlotArea area : this.getPlotAreaManager().getPlotAreasSet(world)) { set.addAll(area.getClusters()); } return Collections.unmodifiableSet(set); @@ -764,13 +629,13 @@ public class PlotSquared { // group by world // sort each HashMap> map = new HashMap<>(); - int totalSize = getPlotCount(); + int totalSize = Arrays.stream(this.getPlotAreaManager().getAllPlotAreas()).mapToInt(PlotArea::getPlotCount).sum(); if (plots.size() == totalSize) { - for (PlotArea area : plotAreaManager.getAllPlotAreas()) { + for (PlotArea area : getPlotAreaManager().getAllPlotAreas()) { map.put(area, area.getPlots()); } } else { - for (PlotArea area : plotAreaManager.getAllPlotAreas()) { + for (PlotArea area : getPlotAreaManager().getAllPlotAreas()) { map.put(area, new ArrayList<>(0)); } Collection lastList = null; @@ -785,7 +650,7 @@ public class PlotSquared { } } } - List areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); + List areas = Arrays.asList(getPlotAreaManager().getAllPlotAreas()); areas.sort((a, b) -> { if (priorityArea != null) { if (a.equals(priorityArea)) { @@ -818,199 +683,25 @@ public class PlotSquared { return toReturn; } - /** - * A more generic way to filter plots - make your own method - * if you need complex filters. - * - * @param filters the filter - * @return a filtered set of plots - * @deprecated Use {@link PlotQuery} - */ - @Deprecated public Set getPlots(final PlotFilter... filters) { - final List areas = new LinkedList<>(); - for (final PlotArea plotArea : this.getPlotAreas()) { - for (final PlotFilter filter : filters) { - if (filter.allowsArea(plotArea)) { - areas.add(plotArea); - } - } - } - return PlotQuery.newQuery().inAreas(areas).thatPasses(plot -> { - for (final PlotFilter filter : filters) { - if (!filter.allowsPlot(plot)) { - return false; - } - } - return true; - }).asSet(); - } - - /** - * Gets all the plots across all plotworlds in one {@code Set}. - * - * @return all the plots on the server loaded by this plugin - */ - public Set getPlots() { - int size = getPlotCount(); - final Set result = new HashSet<>(size); - forEachPlotArea(value -> result.addAll(value.getPlots())); - return result; - } - - public void setPlots(HashMap> plots) { + public void setPlots(@Nonnull final Map> plots) { if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } - for (Entry> entry : plots.entrySet()) { - String world = entry.getKey(); - PlotArea area = getPlotArea(world, null); - if (area == null) { - HashMap map = - this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); + for (final Entry> entry : plots.entrySet()) { + final String world = entry.getKey(); + final PlotArea plotArea = this.getPlotAreaManager().getPlotArea(world, null); + if (plotArea == null) { + Map map = this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); map.putAll(entry.getValue()); } else { for (Plot plot : entry.getValue().values()) { - plot.setArea(area); - area.addPlot(plot); + plot.setArea(plotArea); + plotArea.addPlot(plot); } } } } - /** - * Gets all the plots owned by a player name. - * - * @param world the world - * @param player the plot owner - * @return Set of Plot - */ - public Set getPlots(String world, String player) { - final UUID uuid = this.impromptuUUIDPipeline.getSingle(player, Settings.UUID.BLOCKING_TIMEOUT); - return getPlots(world, uuid); - } - - /** - * Gets all the plots owned by a player name. - * - * @param area the PlotArea - * @param player the plot owner - * @return Set of Plot - */ - public Set getPlots(PlotArea area, String player) { - final UUID uuid = this.impromptuUUIDPipeline.getSingle(player, Settings.UUID.BLOCKING_TIMEOUT); - return getPlots(area, uuid); - } - - /** - * Gets all plots by a PlotPlayer. - * - * @param world the world - * @param player the plot owner - * @return Set of plot - */ - public Set getPlots(String world, PlotPlayer player) { - return PlotQuery.newQuery().inWorld(world).ownedBy(player).asSet(); - } - - /** - * Gets all plots by a PlotPlayer. - * - * @param area the PlotArea - * @param player the plot owner - * @return Set of plot - */ - public Set getPlots(PlotArea area, PlotPlayer player) { - return PlotQuery.newQuery().inArea(area).ownedBy(player).asSet(); - } - - /** - * Gets all plots by a UUID in a world. - * - * @param world the world - * @param uuid the plot owner - * @return Set of plot - */ - public Set getPlots(String world, UUID uuid) { - return PlotQuery.newQuery().inWorld(world).ownedBy(uuid).asSet(); - } - - /** - * Gets all plots by a UUID in an area. - * - * @param area the {@code PlotArea} - * @param uuid the plot owner - * @return Set of plots - */ - public Set getPlots(PlotArea area, UUID uuid) { - return PlotQuery.newQuery().inArea(area).ownedBy(uuid).asSet(); - } - - /** - * Check if a plot world. - * - * @param world the world - * @return if a plot world is registered - * @see #getPlotAreaByString(String) to get the PlotArea object - */ - public boolean hasPlotArea(String world) { - return plotAreaManager.getPlotAreas(world, null).length != 0; - } - - public Collection getPlots(String world) { - return PlotQuery.newQuery().inWorld(world).asCollection(); - } - - /** - * Gets the plots for a PlotPlayer. - * - * @param player the player to retrieve the plots for - * @return Set of Plot - */ - public Set getPlots(PlotPlayer player) { - return PlotQuery.newQuery().ownedBy(player).asSet(); - } - - public Collection getPlots(PlotArea area) { - return area == null ? EMPTY_SET : area.getPlots(); - } - - public Plot getPlot(PlotArea area, PlotId id) { - return area == null ? null : id == null ? null : area.getPlot(id); - } - - public Set getBasePlots(PlotPlayer player) { - return getBasePlots(player.getUUID()); - } - - /** - * Gets the plots for a UUID. - * - * @param uuid the plot owner - * @return Set of Plot's owned by the player - */ - public Set getPlots(final UUID uuid) { - return PlotQuery.newQuery().ownedBy(uuid).asSet(); - } - - public boolean hasPlot(final UUID uuid) { - return Arrays.stream(plotAreaManager.getAllPlotAreas()) - .anyMatch(area -> area.hasPlot(uuid)); - } - - public Set getBasePlots(final UUID uuid) { - return PlotQuery.newQuery().ownedBy(uuid).whereBasePlot().asSet(); - } - - /** - * Gets the plots for a UUID. - * - * @param uuid the UUID of the owner - * @return Set of Plot - */ - public Set getPlotsAbs(final UUID uuid) { - return PlotQuery.newQuery().ownedBy(uuid).asSet(); - } - /** * Unregisters a plot from local memory without calling the database. * @@ -1059,15 +750,15 @@ public class PlotSquared { if (world.equals("CheckingPlotSquaredGenerator")) { return; } - this.plotAreaManager.addWorld(world); + this.getPlotAreaManager().addWorld(world); Set worlds; - if (this.worlds.contains("worlds")) { - worlds = this.worlds.getConfigurationSection("worlds").getKeys(false); + if (this.worldConfiguration.contains("worlds")) { + worlds = this.worldConfiguration.getConfigurationSection("worlds").getKeys(false); } else { worlds = new HashSet<>(); } String path = "worlds." + world; - ConfigurationSection worldSection = this.worlds.getConfigurationSection(path); + ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection(path); PlotAreaType type; if (worldSection != null) { type = MainUtil.getType(worldSection); @@ -1075,7 +766,7 @@ public class PlotSquared { type = PlotAreaType.NORMAL; } if (type == PlotAreaType.NORMAL) { - if (plotAreaManager.getPlotAreas(world, null).length != 0) { + if (getPlotAreaManager().getPlotAreas(world, null).length != 0) { return; } IndependentPlotGenerator plotGenerator; @@ -1084,13 +775,13 @@ public class PlotSquared { } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); GeneratorWrapper secondaryGenerator = - this.IMP.getGenerator(world, secondaryGeneratorName); + this.platform.getGenerator(world, secondaryGeneratorName); if (secondaryGenerator != null && secondaryGenerator.isFull()) { plotGenerator = secondaryGenerator.getPlotGenerator(); } else { String primaryGeneratorName = worldSection.getString("generator.init"); GeneratorWrapper primaryGenerator = - this.IMP.getGenerator(world, primaryGeneratorName); + this.platform.getGenerator(world, primaryGeneratorName); if (primaryGenerator != null && primaryGenerator.isFull()) { plotGenerator = primaryGenerator.getPlotGenerator(); } else { @@ -1107,14 +798,14 @@ public class PlotSquared { logger.info("[P2] - generator: {}>{}", baseGenerator, plotGenerator); logger.info("[P2] - plot world: {}", plotArea.getClass().getCanonicalName()); logger.info("[P2] - plot area manager: {}", plotManager.getClass().getCanonicalName()); - if (!this.worlds.contains(path)) { - this.worlds.createSection(path); - worldSection = this.worlds.getConfigurationSection(path); + if (!this.worldConfiguration.contains(path)) { + this.worldConfiguration.createSection(path); + worldSection = this.worldConfiguration.getConfigurationSection(path); } plotArea.saveConfiguration(worldSection); plotArea.loadDefaultConfiguration(worldSection); try { - this.worlds.save(this.worldsFile); + this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } @@ -1127,14 +818,14 @@ public class PlotSquared { } ConfigurationSection areasSection = worldSection.getConfigurationSection("areas"); if (areasSection == null) { - if (plotAreaManager.getPlotAreas(world, null).length != 0) { + if (getPlotAreaManager().getPlotAreas(world, null).length != 0) { return; } logger.info("[P2] Detected world load for '{}'", world); - String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); + String gen_string = worldSection.getString("generator.plugin", platform.getPluginName()); if (type == PlotAreaType.PARTIAL) { Set clusters = - this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet<>(); + this.clustersTmp != null ? this.clustersTmp.get(world) : new HashSet<>(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } @@ -1147,7 +838,7 @@ public class PlotSquared { worldSection.createSection("areas." + fullId); DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE logger.info("[P2] - {}-{}-{}", name, pos1, pos2); - GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); + GeneratorWrapper areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1156,7 +847,7 @@ public class PlotSquared { pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { - this.worlds.save(this.worldsFile); + this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } @@ -1173,7 +864,7 @@ public class PlotSquared { } return; } - GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); + GeneratorWrapper areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1181,7 +872,7 @@ public class PlotSquared { pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { - this.worlds.save(this.worldsFile); + this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } @@ -1212,7 +903,7 @@ public class PlotSquared { throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); } - PlotArea existing = getPlotArea(world, name); + final PlotArea existing = this.getPlotAreaManager().getPlotArea(world, name); if (existing != null && name.equals(existing.getId())) { continue; } @@ -1234,8 +925,8 @@ public class PlotSquared { clone.set(key, worldSection.get(key)); } } - String gen_string = clone.getString("generator.plugin", IMP.getPluginName()); - GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); + String gen_string = clone.getString("generator.plugin", platform.getPluginName()); + GeneratorWrapper areaGen = this.platform.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } @@ -1257,7 +948,7 @@ public class PlotSquared { } pa.loadDefaultConfiguration(clone); try { - this.worlds.save(this.worldsFile); + this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } @@ -1329,7 +1020,9 @@ public class PlotSquared { split = combinedArgs; } - HybridPlotWorld plotworld = new HybridPlotWorld(world, null, generator, null, null); + final HybridPlotWorldFactory hybridPlotWorldFactory = this.platform.getInjector().getInstance(HybridPlotWorldFactory.class); + final HybridPlotWorld plotWorld = hybridPlotWorldFactory.create(world, null, generator, null, null); + for (String element : split) { String[] pair = element.split("="); if (pair.length != 2) { @@ -1343,41 +1036,41 @@ public class PlotSquared { switch (key) { case "s": case "size": - this.worlds.set(base + "plot.size", + this.worldConfiguration.set(base + "plot.size", ConfigurationUtil.INTEGER.parseString(value).shortValue()); break; case "g": case "gap": - this.worlds.set(base + "road.width", + this.worldConfiguration.set(base + "road.width", ConfigurationUtil.INTEGER.parseString(value).shortValue()); break; case "h": case "height": - this.worlds.set(base + "road.height", + this.worldConfiguration.set(base + "road.height", ConfigurationUtil.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "plot.height", + this.worldConfiguration.set(base + "plot.height", ConfigurationUtil.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "wall.height", + this.worldConfiguration.set(base + "wall.height", ConfigurationUtil.INTEGER.parseString(value).shortValue()); break; case "f": case "floor": - this.worlds.set(base + "plot.floor", + this.worldConfiguration.set(base + "plot.floor", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString()); break; case "m": case "main": - this.worlds.set(base + "plot.filling", + this.worldConfiguration.set(base + "plot.filling", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString()); break; case "w": case "wall": - this.worlds.set(base + "wall.filling", + this.worldConfiguration.set(base + "wall.filling", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString()); break; case "b": case "border": - this.worlds.set(base + "wall.block", + this.worldConfiguration.set(base + "wall.block", ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString()); break; default: @@ -1392,10 +1085,10 @@ public class PlotSquared { } try { ConfigurationSection section = - this.worlds.getConfigurationSection("worlds." + world); - plotworld.saveConfiguration(section); - plotworld.loadDefaultConfiguration(section); - this.worlds.save(this.worldsFile); + this.worldConfiguration.getConfigurationSection("worlds." + world); + plotWorld.saveConfiguration(section); + plotWorld.loadDefaultConfiguration(section); + this.worldConfiguration.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); } @@ -1403,17 +1096,6 @@ public class PlotSquared { return true; } - public boolean canUpdate(@NonNull final String current, @NonNull final String other) { - final String s1 = normalisedVersion(current); - final String s2 = normalisedVersion(other); - return s1.compareTo(s2) < 0; - } - - public String normalisedVersion(@NonNull final String version) { - final String[] split = Pattern.compile(".", Pattern.LITERAL).split(version); - return Arrays.stream(split).map(s -> String.format("%4s", s)).collect(Collectors.joining()); - } - /** * Copies a file from inside the jar to a location * @@ -1422,7 +1104,7 @@ public class PlotSquared { */ public void copyFile(String file, String folder) { try { - File output = this.IMP.getDirectory(); + File output = this.platform.getDirectory(); if (!output.exists()) { output.mkdirs(); } @@ -1430,7 +1112,7 @@ public class PlotSquared { if (newFile.exists()) { return; } - try (InputStream stream = this.IMP.getClass().getResourceAsStream(file)) { + try (InputStream stream = this.platform.getClass().getResourceAsStream(file)) { byte[] buffer = new byte[2048]; if (stream == null) { try (ZipInputStream zis = new ZipInputStream( @@ -1469,19 +1151,6 @@ public class PlotSquared { } } - private Map> getPlotsRaw() { - HashMap> map = new HashMap<>(); - for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - Map map2 = map.get(area.toString()); - if (map2 == null) { - map.put(area.toString(), area.getPlotsMap()); - } else { - map2.putAll(area.getPlotsMap()); - } - } - return map; - } - /** * Safely closes the database connection. */ @@ -1529,7 +1198,7 @@ public class PlotSquared { list.add(chunks); list.add(HybridUtils.height); File file = new File( - this.IMP.getDirectory() + File.separator + "persistent_regen_data_" + HybridUtils.area + this.platform.getDirectory() + File.separator + "persistent_regen_data_" + HybridUtils.area .getId() + "_" + HybridUtils.area.getWorldName()); if (file.exists() && !file.delete()) { logger.error("[P2] persistent_regene_data file already exists and could not be deleted"); @@ -1556,34 +1225,34 @@ public class PlotSquared { database = new MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, Storage.MySQL.USER, Storage.MySQL.PASSWORD); } else if (Storage.SQLite.USE) { - File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db"); + File file = MainUtil.getFile(platform.getDirectory(), Storage.SQLite.DB + ".db"); database = new SQLite(file); } else { logger.error("[P2] No storage type is set. Disabling PlotSquared"); - this.IMP.shutdown(); //shutdown used instead of disable because no database is set + this.platform.shutdown(); //shutdown used instead of disable because no database is set return; } - DBFunc.dbManager = new SQLManager(database, Storage.PREFIX, false); + DBFunc.dbManager = new SQLManager(database, Storage.PREFIX, this.eventDispatcher, this.plotListener, this.worldConfiguration); this.plots_tmp = DBFunc.getPlots(); - if (plotAreaManager instanceof SinglePlotAreaManager) { - SinglePlotArea area = ((SinglePlotAreaManager) plotAreaManager).getArea(); + if (getPlotAreaManager() instanceof SinglePlotAreaManager) { + SinglePlotArea area = ((SinglePlotAreaManager) getPlotAreaManager()).getArea(); addPlotArea(area); - ConfigurationSection section = worlds.getConfigurationSection("worlds.*"); + ConfigurationSection section = worldConfiguration.getConfigurationSection("worlds.*"); if (section == null) { - section = worlds.createSection("worlds.*"); + section = worldConfiguration.createSection("worlds.*"); } area.saveConfiguration(section); area.loadDefaultConfiguration(section); } - this.clusters_tmp = DBFunc.getClusters(); + this.clustersTmp = DBFunc.getClusters(); } catch (ClassNotFoundException | SQLException e) { logger.error("[P2] Failed to open database connection ({}). Disabling PlotSquared", Storage.MySQL.USE ? "MySQL" : "SQLite"); logger.error("[P2] ==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); logger.error("[P2] &d==== End of stacktrace ===="); logger.error("[P2] &6Please go to the {} 'storage.yml' and configure the database correctly", - imp().getPluginName()); - this.IMP.shutdown(); //shutdown used instead of disable because of database error + platform.getPluginName()); + this.platform.shutdown(); //shutdown used instead of disable because of database error } } @@ -1603,9 +1272,9 @@ public class PlotSquared { if (getConfig().contains("worlds")) { ConfigurationSection worldSection = getConfig().getConfigurationSection("worlds"); - worlds.set("worlds", worldSection); + worldConfiguration.set("worlds", worldSection); try { - worlds.save(worldsFile); + worldConfiguration.save(worldsFile); } catch (IOException e) { logger.error("[P2] Failed to save worlds.yml", e); e.printStackTrace(); @@ -1638,7 +1307,7 @@ public class PlotSquared { * - Translation: PlotSquared.use_THIS.yml, style.yml
    */ public boolean setupConfigs() { - File folder = new File(this.IMP.getDirectory(), "config"); + File folder = new File(this.platform.getDirectory(), "config"); if (!folder.exists() && !folder.mkdirs()) { logger.error("[P2] Failed to create the /plugins/config folder. Please create it manually"); } @@ -1647,12 +1316,12 @@ public class PlotSquared { if (!this.worldsFile.exists() && !this.worldsFile.createNewFile()) { logger.error("[P2] Could not create the worlds file. Please create 'worlds.yml' manually"); } - this.worlds = YamlConfiguration.loadConfiguration(this.worldsFile); + this.worldConfiguration = YamlConfiguration.loadConfiguration(this.worldsFile); - if (this.worlds.contains("worlds")) { - if (!this.worlds.contains("configuration_version") || ( - !this.worlds.getString("configuration_version") - .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION) && !this.worlds + if (this.worldConfiguration.contains("worlds")) { + if (!this.worldConfiguration.contains("configuration_version") || ( + !this.worldConfiguration.getString("configuration_version") + .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION) && !this.worldConfiguration .getString("configuration_version").equalsIgnoreCase("v5"))) { // Conversion needed logger.info(Captions.LEGACY_CONFIG_FOUND.getTranslated()); @@ -1661,21 +1330,21 @@ public class PlotSquared { .copy(this.worldsFile, new File(folder, "worlds.yml.old")); logger.info(Captions.LEGACY_CONFIG_BACKUP.getTranslated()); final ConfigurationSection worlds = - this.worlds.getConfigurationSection("worlds"); + this.worldConfiguration.getConfigurationSection("worlds"); final LegacyConverter converter = new LegacyConverter(worlds); converter.convert(); - this.worlds.set("worlds", worlds); + this.worldConfiguration.set("worlds", worlds); this.setConfigurationVersion(LegacyConverter.CONFIGURATION_VERSION); logger.info(Captions.LEGACY_CONFIG_DONE.getTranslated()); } catch (final Exception e) { logger.error(Captions.LEGACY_CONFIG_CONVERSION_FAILED.getTranslated(), e); } // Disable plugin - this.IMP.shutdown(); + this.platform.shutdown(); return false; } } else { - this.worlds.set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); + this.worldConfiguration.set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); } } catch (IOException ignored) { logger.error("[P2] Failed to save worlds.yml"); @@ -1691,17 +1360,18 @@ public class PlotSquared { logger.error("[P2] Failed to save settings.yml"); } try { - this.styleFile = MainUtil.getFile(IMP.getDirectory(), + // TODO: REMOVE + File styleFile = MainUtil.getFile(platform.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + "style.yml"); - if (!this.styleFile.exists()) { - if (!this.styleFile.getParentFile().exists()) { - this.styleFile.getParentFile().mkdirs(); + if (!styleFile.exists()) { + if (!styleFile.getParentFile().exists()) { + styleFile.getParentFile().mkdirs(); } - if (!this.styleFile.createNewFile()) { + if (!styleFile.createNewFile()) { logger.error("[P2] Failed to create the style file. Please create 'translations/style.yml' manually"); } } - this.style = YamlConfiguration.loadConfiguration(this.styleFile); + this.style = YamlConfiguration.loadConfiguration(styleFile); setupStyle(); } catch (IOException ignored) { logger.error("[P2] Failed to save style.yml"); @@ -1711,27 +1381,22 @@ public class PlotSquared { if (!this.storageFile.exists() && !this.storageFile.createNewFile()) { logger.error("[P2] Could not create the storage settings file. Please create 'storage.yml' manually"); } - this.storage = YamlConfiguration.loadConfiguration(this.storageFile); + YamlConfiguration.loadConfiguration(this.storageFile); setupStorage(); } catch (IOException ignored) { logger.error("[P2] Failed to save storage.yml"); } - try { - this.style.save(this.styleFile); - } catch (IOException e) { - logger.error("[P2] Configuration file saving failed", e); - } return true; } public String getConfigurationVersion() { - return this.worlds.get("configuration_version", LegacyConverter.CONFIGURATION_VERSION) + return this.worldConfiguration.get("configuration_version", LegacyConverter.CONFIGURATION_VERSION) .toString(); } public void setConfigurationVersion(final String newVersion) throws IOException { - this.worlds.set("configuration_version", newVersion); - this.worlds.save(this.worldsFile); + this.worldConfiguration.set("configuration_version", newVersion); + this.worldConfiguration.save(this.worldsFile); } /** @@ -1740,7 +1405,7 @@ public class PlotSquared { private void setupStorage() { Storage.load(storageFile); Storage.save(storageFile); - storage = YamlConfiguration.loadConfiguration(storageFile); + YamlConfiguration.loadConfiguration(storageFile); } /** @@ -1793,39 +1458,8 @@ public class PlotSquared { } } - /** - * Gets the Java version. - * - * @return the java version - */ - private double getJavaVersion() { - return Double.parseDouble(System.getProperty("java.specification.version")); - } - - public void forEachPlotArea(Consumer action) { - for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - action.accept(area); - } - } - - public void forEachPlotArea(@NonNull final String world, Consumer consumer) { - final PlotArea[] array = this.plotAreaManager.getPlotAreas(world, null); - if (array == null) { - return; - } - for (final PlotArea area : array) { - consumer.accept(area); - } - } - - public void forEachPlot(Consumer consumer) { - for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - area.getPlots().forEach(consumer); - } - } - public void forEachPlotRaw(Consumer consumer) { - for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { + for (final PlotArea area : this.getPlotAreaManager().getAllPlotAreas()) { area.getPlots().forEach(consumer); } if (this.plots_tmp != null) { @@ -1835,32 +1469,6 @@ public class PlotSquared { } } - public void forEachBasePlot(Consumer consumer) { - for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - area.forEachBasePlot(consumer); - } - } - - public PlotArea getFirstPlotArea() { - PlotArea[] areas = plotAreaManager.getAllPlotAreas(); - return areas.length > 0 ? areas[0] : null; - } - - public int getPlotAreaCount() { - return this.plotAreaManager.getAllPlotAreas().length; - } - - public int getPlotCount() { - return Arrays.stream(this.plotAreaManager.getAllPlotAreas()) - .mapToInt(PlotArea::getPlotCount).sum(); - } - - public Set getPlotAreas() { - final Set set = new HashSet<>(); - Collections.addAll(set, plotAreaManager.getAllPlotAreas()); - return Collections.unmodifiableSet(set); - } - /** * Check if the chunk uses vanilla/non-PlotSquared generation * @@ -1868,115 +1476,16 @@ public class PlotSquared { * @param chunkCoordinates Chunk coordinates * @return True if the chunk uses non-standard generation, false if not */ - public boolean isNonStandardGeneration(@NotNull final String world, - @NotNull final BlockVector2 chunkCoordinates) { - final Location location = new Location(world, chunkCoordinates.getBlockX() << 4, 64, chunkCoordinates.getBlockZ() << 4); - final PlotArea area = plotAreaManager.getApplicablePlotArea(location); + public boolean isNonStandardGeneration(@Nonnull final String world, + @Nonnull final BlockVector2 chunkCoordinates) { + final Location location = Location.at(world, chunkCoordinates.getBlockX() << 4, 64, chunkCoordinates.getBlockZ() << 4); + final PlotArea area = getPlotAreaManager().getApplicablePlotArea(location); if (area == null) { return true; } return area.getTerrain() != PlotAreaTerrainType.NONE; } - public boolean isAugmented(@NonNull final String world) { - final PlotArea[] areas = plotAreaManager.getPlotAreas(world, null); - return areas != null && (areas.length > 1 || areas[0].getType() != PlotAreaType.NORMAL); - } - - /** - * Gets a list of PlotArea objects. - * - * @param world the world - * @return Collection of PlotArea objects - */ - public Set getPlotAreas(@NonNull final String world) { - final Set set = new HashSet<>(); - Collections.addAll(set, plotAreaManager.getPlotAreas(world, null)); - return set; - } - - /** - * Gets the relevant plot area for a specified location. - *

      - *
    • If there is only one plot area globally that will be returned. - *
    • If there is only one plot area in the world, it will return that. - *
    • If the plot area for a location cannot be unambiguously - * resolved, null will be returned. - *
    - * Note: An applicable plot area may not include the location i.e. clusters - * - * @param location the location - * @return - */ - public PlotArea getApplicablePlotArea(@NonNull final Location location) { - return plotAreaManager.getApplicablePlotArea(location); - } - - public PlotArea getPlotArea(@NonNull final String world, final String id) { - return plotAreaManager.getPlotArea(world, id); - } - - /** - * Gets the {@code PlotArea} which contains a location. - *
      - *
    • If the plot area does not contain a location, null - * will be returned. - *
    - * - * @param location the location - * @return the {@link PlotArea} in the location, null if non existent - */ - public PlotArea getPlotAreaAbs(@NonNull final Location location) { - return plotAreaManager.getPlotArea(location); - } - - public PlotArea getPlotAreaByString(@NonNull final String search) { - String[] split = search.split("[;,]"); - PlotArea[] areas = plotAreaManager.getPlotAreas(split[0], null); - if (areas == null) { - for (PlotArea area : plotAreaManager.getAllPlotAreas()) { - if (area.getWorldName().equalsIgnoreCase(split[0])) { - if (area.getId() == null || split.length == 2 && area.getId() - .equalsIgnoreCase(split[1])) { - return area; - } - } - } - return null; - } - if (areas.length == 1) { - return areas[0]; - } else if (split.length == 1) { - return null; - } else { - for (PlotArea area : areas) { - if (StringMan.isEqual(split[1], area.getId())) { - return area; - } - } - return null; - } - } - - /** - * Gets Plots based on alias - * - * @param alias to search plots - * @param worldname to filter alias to a specific world [optional] null means all worlds - * @return Set<{@link Plot }> empty if nothing found - */ - public Set getPlotsByAlias(@Nullable final String alias, - @NonNull final String worldname) { - return PlotQuery.newQuery().inWorld(worldname).withAlias(alias).asSet(); - } - - public Set getPlotAreas(final String world, final CuboidRegion region) { - final PlotArea[] areas = plotAreaManager.getPlotAreas(world, region); - final Set set = new HashSet<>(); - Collections.addAll(set, areas); - return Collections.unmodifiableSet(set); - } - public YamlConfiguration getConfig() { return config; } diff --git a/Core/src/main/java/com/plotsquared/core/backup/Backup.java b/Core/src/main/java/com/plotsquared/core/backup/Backup.java index a84fc497f..111edd8a7 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/Backup.java +++ b/Core/src/main/java/com/plotsquared/core/backup/Backup.java @@ -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; diff --git a/Core/src/main/java/com/plotsquared/core/backup/BackupManager.java b/Core/src/main/java/com/plotsquared/core/backup/BackupManager.java index 4ba4a44f4..5ae0dcdfe 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/BackupManager.java +++ b/Core/src/main/java/com/plotsquared/core/backup/BackupManager.java @@ -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 diff --git a/Core/src/main/java/com/plotsquared/core/backup/BackupProfile.java b/Core/src/main/java/com/plotsquared/core/backup/BackupProfile.java index 6664246e4..1a9dc7baa 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/BackupProfile.java +++ b/Core/src/main/java/com/plotsquared/core/backup/BackupProfile.java @@ -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> listBackups(); + @Nonnull CompletableFuture> 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 createBackup(); + @Nonnull CompletableFuture 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 restoreBackup(@NotNull final Backup backup); + @Nonnull CompletableFuture restoreBackup(@Nonnull final Backup backup); } diff --git a/Core/src/main/java/com/plotsquared/core/backup/NullBackupManager.java b/Core/src/main/java/com/plotsquared/core/backup/NullBackupManager.java index 2d8c04a76..c83a36c24 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/NullBackupManager.java +++ b/Core/src/main/java/com/plotsquared/core/backup/NullBackupManager.java @@ -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() { diff --git a/Core/src/main/java/com/plotsquared/core/backup/NullBackupProfile.java b/Core/src/main/java/com/plotsquared/core/backup/NullBackupProfile.java index 39c833579..b16a589fc 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/NullBackupProfile.java +++ b/Core/src/main/java/com/plotsquared/core/backup/NullBackupProfile.java @@ -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> listBackups() { + @Override @Nonnull public CompletableFuture> 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 createBackup() { + @Override @Nonnull public CompletableFuture createBackup() { throw new UnsupportedOperationException("Cannot create backup of an unowned plot"); } - @Override @NotNull public CompletableFuture restoreBackup(@NotNull final Backup backup) { + @Override @Nonnull public CompletableFuture restoreBackup(@Nonnull final Backup backup) { return CompletableFuture.completedFuture(null); } diff --git a/Core/src/main/java/com/plotsquared/core/backup/PlayerBackupProfile.java b/Core/src/main/java/com/plotsquared/core/backup/PlayerBackupProfile.java index c71057ab5..e70ef4ac6 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/PlayerBackupProfile.java +++ b/Core/src/main/java/com/plotsquared/core/backup/PlayerBackupProfile.java @@ -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 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> listBackups() { + @Override @Nonnull public CompletableFuture> 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 createBackup() { + @Override @Nonnull public CompletableFuture createBackup() { final CompletableFuture 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 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 restoreBackup(@NotNull final Backup backup) { + @Override @Nonnull public CompletableFuture restoreBackup(@Nonnull final Backup backup) { final CompletableFuture 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() { + this.schematicHandler.paste(schematic, plot, 0, 1, 0, false, new RunnableVal() { @Override public void run(Boolean value) { if (value) { future.complete(null); diff --git a/Core/src/main/java/com/plotsquared/core/backup/SimpleBackupManager.java b/Core/src/main/java/com/plotsquared/core/backup/SimpleBackupManager.java index 57cbea1d8..97bae8f1c 100644 --- a/Core/src/main/java/com/plotsquared/core/backup/SimpleBackupManager.java +++ b/Core/src/main/java/com/plotsquared/core/backup/SimpleBackupManager.java @@ -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 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(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Add.java b/Core/src/main/java/com/plotsquared/core/command/Add.java index 6d86f7532..b1843fffd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Add.java +++ b/Core/src/main/java/com/plotsquared/core/command/Add.java @@ -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.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 java.util.Collection; import java.util.Collections; @@ -51,8 +53,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 @@ -116,7 +121,7 @@ public class Add extends Command { } } plot.addMember(uuid); - PlotSquared.get().getEventDispatcher().callMember(player, plot, uuid, true); + this.eventDispatcher.callMember(player, plot, uuid, true); MainUtil.sendMessage(player, Captions.MEMBER_ADDED); } }, null); diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index 383076f0d..18f71b00f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -25,13 +25,18 @@ */ 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.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,7 @@ 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; @@ -65,11 +71,14 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; +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; @@ -83,6 +92,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) { Captions.COMMAND_SYNTAX.send(player, getUsage()); @@ -102,7 +135,7 @@ public class Area extends SubCommand { MainUtil.sendMessage(player, Captions.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])) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_NAME_TAKEN); return false; @@ -124,7 +157,7 @@ public class Area extends SubCommand { MainUtil.sendMessage(player, Captions.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) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_OVERLAPPING); } @@ -137,8 +170,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 @@ -153,7 +186,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()) { @@ -187,8 +220,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 = () -> { @@ -198,15 +231,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); MainUtil.sendMessage(player, Captions.SINGLE_AREA_CREATED); } else { @@ -274,16 +305,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 areas = - PlotSquared.get().getPlotAreas(area.getWorldName(), region); + final Set areas = this.plotAreaManager + .getPlotAreasSet(area.getWorldName(), region); if (!areas.isEmpty()) { Captions.CLUSTER_INTERSECTION .send(player, 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 = @@ -291,21 +322,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); Captions.SETUP_FINISHED.send(player); - 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() { @Override public void run(BlockVector2 value) { AugmentedUtils @@ -336,16 +365,16 @@ 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())) { Captions.SETUP_WORLD_TAKEN.send(player, pa.toString()); return false; } - Set areas = PlotSquared.get().getPlotAreas(pa.getWorldName()); + Set areas = this.plotAreaManager.getPlotAreasSet(pa.getWorldName()); if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); pa.setType(area.getType()); @@ -415,25 +444,24 @@ public class Area extends SubCommand { } } if (pa.getType() != PlotAreaType.PARTIAL) { - if (WorldUtil.IMP.isWorld(pa.getWorldName())) { + if (this.worldUtil.isWorld(pa.getWorldName())) { Captions.SETUP_WORLD_TAKEN.send(player, 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)) { Captions.SETUP_FINISHED.send(player); - player.teleport(WorldUtil.IMP.getSpawn(world), + player.teleport(this.worldUtil.getSpawn(world), TeleportCause.COMMAND); } else { MainUtil.sendMessage(player, @@ -441,7 +469,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(); } @@ -459,16 +487,16 @@ public class Area extends SubCommand { + " create [world[:id]] [=]..."); 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); @@ -490,7 +518,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]"); @@ -552,7 +580,7 @@ public class Area extends SubCommand { Captions.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]"); return false; } - ArrayList areas = new ArrayList<>(PlotSquared.get().getPlotAreas()); + final List areas = new ArrayList<>(Arrays.asList(this.plotAreaManager.getAllPlotAreas())); paginate(player, areas, 8, page, new RunnableVal3() { @Override public void run(Integer i, PlotArea area, PlotMessage message) { @@ -612,7 +640,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() { @Override public void run(BlockVector2 value) { AugmentedUtils @@ -635,33 +663,30 @@ 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) { Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; } 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."); diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index 4c75de3f8..e212d3e58 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -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,14 +41,17 @@ 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; import com.plotsquared.core.util.task.AutoClaimFinishTask; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; -import org.jetbrains.annotations.Nullable; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Set; @@ -61,6 +65,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); } @@ -136,7 +152,8 @@ public class Auto extends SubCommand { player.setMeta(Auto.class.getName(), true); autoClaimFromDatabase(player, area, start, new RunnableVal() { @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())); } }); } @@ -157,10 +174,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; @@ -169,8 +185,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) { MainUtil.sendMessage(player, Captions.NOT_IN_PLOT_WORLD); @@ -213,7 +229,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"); @@ -253,18 +269,18 @@ public class Auto extends SubCommand { return true; } } - if (EconHandler.getEconHandler() != null && plotarea.useEconomy()) { + if (this.econHandler != null && plotarea.useEconomy()) { Expression 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 + ""); } } @@ -294,7 +310,7 @@ public class Auto extends SubCommand { } ArrayList 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"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Backup.java b/Core/src/main/java/com/plotsquared/core/command/Backup.java index 944eaaf6b..4c16458c6 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Backup.java +++ b/Core/src/main/java/com/plotsquared/core/command/Backup.java @@ -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> 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()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Buy.java b/Core/src/main/java/com/plotsquared/core/command/Buy.java index 337801385..f62f24bc2 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Buy.java +++ b/Core/src/main/java/com/plotsquared/core/command/Buy.java @@ -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 confirm, final RunnableVal2 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()); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Caps.java b/Core/src/main/java/com/plotsquared/core/command/Caps.java index b56d33dc0..55efd2519 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Caps.java +++ b/Core/src/main/java/com/plotsquared/core/command/Caps.java @@ -71,7 +71,7 @@ public class Caps extends SubCommand { } private > void sendFormatted(final Plot plot, - final PlotPlayer player, final Class capFlag, final int[] countedEntities, + final PlotPlayer player, final Class capFlag, final int[] countedEntities, final String name, final int type) { final int current = countedEntities[type]; final int max = plot.getFlag(capFlag); diff --git a/Core/src/main/java/com/plotsquared/core/command/Claim.java b/Core/src/main/java/com/plotsquared/core/command/Claim.java index 2271eaa67..7b51ea6cf 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Claim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Claim.java @@ -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,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.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; @@ -58,18 +62,26 @@ 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"); @@ -78,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")) { @@ -109,14 +121,14 @@ public class Claim extends SubCommand { } } } - if ((EconHandler.getEconHandler() != null) && area.useEconomy() && !force) { + if ((this.econHandler != null) && area.useEconomy() && !force) { Expression 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 + ""); } } @@ -134,7 +146,7 @@ public class Claim extends SubCommand { } plot.setOwnerAbs(player.getUUID()); final String finalSchematic = schematic; - DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal() { + DBFunc.createPlotSafe(plot, () -> TaskManager.getImplementation().sync(new RunnableVal() { @Override public void run(Object value) { if (!plot.claim(player, true, finalSchematic, false)) { logger.info(Captions.PREFIX.getTranslated() + String @@ -142,7 +154,7 @@ public class Claim extends SubCommand { 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"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Clear.java b/Core/src/main/java/com/plotsquared/core/command/Clear.java index 9d8279eda..1eee3a26c 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Clear.java +++ b/Core/src/main/java/com/plotsquared/core/command/Clear.java @@ -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 clear - // The syntax also works with any command: /plot + 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 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()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Cluster.java b/Core/src/main/java/com/plotsquared/core/command/Cluster.java index 557ba084b..0902170bf 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Cluster.java +++ b/Core/src/main/java/com/plotsquared/core/command/Cluster.java @@ -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(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Command.java b/Core/src/main/java/com/plotsquared/core/command/Command.java index 194fc48a4..a0dbe9079 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Command.java +++ b/Core/src/main/java/com/plotsquared/core/command/Command.java @@ -36,7 +36,7 @@ import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal3; import lombok.SneakyThrows; -import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -582,7 +582,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; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Comment.java b/Core/src/main/java/com/plotsquared/core/command/Comment.java index a5615533f..455ec268c 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Comment.java +++ b/Core/src/main/java/com/plotsquared/core/command/Comment.java @@ -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, " ")); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Condense.java b/Core/src/main/java/com/plotsquared/core/command/Condense.java index 8f792ee7e..180e26581 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Condense.java +++ b/Core/src/main/java/com/plotsquared/core/command/Condense.java @@ -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 plots = new ArrayList<>(PlotSquared.get().getPlots(area)); + + final List plots = new ArrayList<>(area.getPlots()); // remove non base plots Iterator iterator = plots.iterator(); int maxSize = 0; diff --git a/Core/src/main/java/com/plotsquared/core/command/Continue.java b/Core/src/main/java/com/plotsquared/core/command/Continue.java index 23f5e93a0..bd061e380 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Continue.java +++ b/Core/src/main/java/com/plotsquared/core/command/Continue.java @@ -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; diff --git a/Core/src/main/java/com/plotsquared/core/command/CreateRoadSchematic.java b/Core/src/main/java/com/plotsquared/core/command/CreateRoadSchematic.java index d5800896a..2820fc204 100644 --- a/Core/src/main/java/com/plotsquared/core/command/CreateRoadSchematic.java +++ b/Core/src/main/java/com/plotsquared/core/command/CreateRoadSchematic.java @@ -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; } diff --git a/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java b/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java index 41690b5af..424363e3f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java @@ -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] ") 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 plots, final PlotPlayer player) { TaskManager.runTaskAsync(() -> { @@ -80,12 +103,12 @@ public class DatabaseCommand extends SubCommand { return false; } List 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 [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> map = manager.getPlots(); plots = new ArrayList<>(); for (Entry> entry : map.entrySet()) { String areaName = entry.getKey(); - PlotArea pa = PlotSquared.get().getPlotAreaByString(areaName); + PlotArea pa = this.plotAreaManager.getPlotAreaByString(areaName); if (pa != null) { for (Entry 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) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Debug.java b/Core/src/main/java/com/plotsquared/core/command/Debug.java index cff10feeb..d8e591313 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Debug.java +++ b/Core/src/main/java/com/plotsquared/core/command/Debug.java @@ -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.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; @@ -52,6 +56,15 @@ 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])) { @@ -65,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; @@ -129,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")); diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java index 7447b625a..387320ffb 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java @@ -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,10 @@ 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; @@ -86,31 +92,43 @@ 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() { @@ -159,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 @@ -205,7 +223,7 @@ public class DebugExec extends SubCommand { return true; } MainUtil.sendMessage(player, "$1Starting task..."); - HybridUtils.manager.analyzePlot(plot, new RunnableVal() { + this.hybridUtils.analyzePlot(plot, new RunnableVal() { @Override public void run(PlotAnalysis value) { MainUtil.sendMessage(player, "$1Done: $2Use $3/plot debugexec analyze$2 for more information"); @@ -250,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()); @@ -264,17 +282,16 @@ public class DebugExec extends SubCommand { "&cInvalid syntax: /plot debugexec start-rgar "); 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, @@ -293,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"); @@ -311,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, @@ -343,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) { @@ -359,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(); diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugImportWorlds.java b/Core/src/main/java/com/plotsquared/core/command/DebugImportWorlds.java index bdb5a13b2..0f15c1528 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugImportWorlds.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugImportWorlds.java @@ -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 confirm, RunnableVal2 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); diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugPaste.java b/Core/src/main/java/com/plotsquared/core/command/DebugPaste.java index 441fbdd84..fa7f4a837 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugPaste.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugPaste.java @@ -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 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, Boolean> pluginInfo : PlotSquared - .get().IMP.getPluginIds()) { + .platform().getPluginIds()) { Map.Entry 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))); diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java b/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java index b20924586..b656522c7 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java @@ -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 "; + 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?)"); diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugSaveTest.java b/Core/src/main/java/com/plotsquared/core/command/DebugSaveTest.java index 7307ca185..598bf26ab 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugSaveTest.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugSaveTest.java @@ -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 plots = new ArrayList<>(PlotSquared.get().getPlots()); + final List plots = PlotQuery.newQuery().allPlots().asList(); MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); DBFunc.createPlotsAndData(plots, () -> MainUtil.sendMessage(player, "&6Database sync finished!")); diff --git a/Core/src/main/java/com/plotsquared/core/command/Delete.java b/Core/src/main/java/com/plotsquared/core/command/Delete.java index 5f8178e06..87d8d683a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Delete.java +++ b/Core/src/main/java/com/plotsquared/core/command/Delete.java @@ -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 delete - // The syntax also works with any command: /plot + 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 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 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)); } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Deny.java b/Core/src/main/java/com/plotsquared/core/command/Deny.java index 1cb862304..b97be84f7 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Deny.java +++ b/Core/src/main/java/com/plotsquared/core/command/Deny.java @@ -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()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Desc.java b/Core/src/main/java/com/plotsquared/core/command/Desc.java index f128920e8..6b607ae31 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Desc.java +++ b/Core/src/main/java/com/plotsquared/core/command/Desc.java @@ -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; diff --git a/Core/src/main/java/com/plotsquared/core/command/Dislike.java b/Core/src/main/java/com/plotsquared/core/command/Dislike.java index 410e13b57..51e0b1ca2 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Dislike.java +++ b/Core/src/main/java/com/plotsquared/core/command/Dislike.java @@ -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); } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Done.java b/Core/src/main/java/com/plotsquared/core/command/Done.java index 258454f8a..2103cc4d9 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Done.java +++ b/Core/src/main/java/com/plotsquared/core/command/Done.java @@ -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() { + this.hybridUtils.analyzePlot(plot, new RunnableVal() { @Override public void run(PlotAnalysis value) { plot.removeRunning(); boolean result = diff --git a/Core/src/main/java/com/plotsquared/core/command/Download.java b/Core/src/main/java/com/plotsquared/core/command/Download.java index efd4079d5..66f0b6e86 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Download.java +++ b/Core/src/main/java/com/plotsquared/core/command/Download.java @@ -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() { + this.schematicHandler.getCompoundTag(plot, new RunnableVal() { @Override public void run(CompoundTag value) { plot.removeRunning(); - SchematicHandler.manager.upload(value, null, null, new RunnableVal() { + schematicHandler.upload(value, null, null, new RunnableVal() { @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() { + this.worldUtil.saveWorld(world); + this.worldUtil.upload(plot, null, null, new RunnableVal() { @Override public void run(URL url) { plot.removeRunning(); if (url == null) { diff --git a/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java b/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java index d6b5a58e8..d71cbbb2b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java @@ -50,8 +50,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; @@ -87,7 +87,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 @@ -152,7 +152,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) { @@ -180,8 +180,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) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Grant.java b/Core/src/main/java/com/plotsquared/core/command/Grant.java index 2d41da2e3..59c1453a8 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Grant.java +++ b/Core/src/main/java/com/plotsquared/core/command/Grant.java @@ -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 { diff --git a/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java b/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java index 38942ad11..3cc72188a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java @@ -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 confirm, final RunnableVal2 whenDone) { List 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 diff --git a/Core/src/main/java/com/plotsquared/core/command/Kick.java b/Core/src/main/java/com/plotsquared/core/command/Kick.java index 911ea9810..1b35df43c 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Kick.java +++ b/Core/src/main/java/com/plotsquared/core/command/Kick.java @@ -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()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Leave.java b/Core/src/main/java/com/plotsquared/core/command/Leave.java index 3a0d7f09d..a6666f84c 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Leave.java +++ b/Core/src/main/java/com/plotsquared/core/command/Leave.java @@ -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 { diff --git a/Core/src/main/java/com/plotsquared/core/command/Like.java b/Core/src/main/java/com/plotsquared/core/command/Like.java index 216c6524c..cab2dc433 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Like.java +++ b/Core/src/main/java/com/plotsquared/core/command/Like.java @@ -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) { diff --git a/Core/src/main/java/com/plotsquared/core/command/ListCmd.java b/Core/src/main/java/com/plotsquared/core/command/ListCmd.java index a08de0cd0..57bbe624a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/ListCmd.java +++ b/Core/src/main/java/com/plotsquared/core/command/ListCmd.java @@ -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; @@ -36,6 +37,7 @@ 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 +49,8 @@ import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.query.SortingStrategy; import com.plotsquared.core.util.task.RunnableVal3; import com.plotsquared.core.uuid.UUIDMapping; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; @@ -69,9 +73,18 @@ import java.util.stream.Collectors; usage = "/plot list > [#]") 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 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 +151,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}; @@ -264,7 +277,7 @@ public class ListCmd extends SubCommand { Captions.PERMISSION_LIST_FOR_SALE); return false; } - if (EconHandler.getEconHandler() == null) { + if (this.econHandler == null) { break; } plotConsumer.accept(PlotQuery.newQuery().allPlots().thatPasses(plot -> plot.getFlag(PriceFlag.class) > 0)); @@ -297,7 +310,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)) { MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_WORLD); @@ -383,7 +396,7 @@ public class ListCmd extends SubCommand { final List 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")); @@ -404,7 +417,7 @@ public class ListCmd extends SubCommand { @Override public Collection tab(PlotPlayer player, String[] args, boolean space) { final List completions = new LinkedList<>(); - if (EconHandler.getEconHandler() != null && Permissions + if (this.econHandler != null && Permissions .hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) { completions.add("forsale"); } @@ -415,7 +428,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"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Load.java b/Core/src/main/java/com/plotsquared/core/command/Load.java index aa952a007..cc099687b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Load.java +++ b/Core/src/main/java/com/plotsquared/core/command/Load.java @@ -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() { @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 schematics1 = SchematicHandler.manager.getSaves(player.getUUID()); + List schematics1 = this.schematicHandler.getSaves(player.getUUID()); plot.removeRunning(); if ((schematics1 == null) || schematics1.isEmpty()) { MainUtil.sendMessage(player, Captions.LOAD_FAILED); diff --git a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java index 0df008815..d724155cf 100644 --- a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java @@ -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.location.Location; @@ -39,6 +41,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; /** @@ -60,90 +64,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> 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 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) { @@ -165,14 +174,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 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(); } @@ -186,12 +195,12 @@ public class MainCommand extends Command { }); return; } - if (EconHandler.getEconHandler() != null) { + if (econHandler != null) { PlotArea area = player.getApplicablePlotArea(); if (area != null) { Expression 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(); } @@ -253,14 +262,14 @@ public class MainCommand extends Command { if ("f".equals(args[0].substring(1))) { confirm = new RunnableVal3() { @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 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(); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Merge.java b/Core/src/main/java/com/plotsquared/core/command/Merge.java index 33754c4b8..49d275246 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Merge.java +++ b/Core/src/main/java/com/plotsquared/core/command/Merge.java @@ -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 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); diff --git a/Core/src/main/java/com/plotsquared/core/command/Move.java b/Core/src/main/java/com/plotsquared/core/command/Move.java index 136bbcfaa..2ae527f54 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Move.java +++ b/Core/src/main/java/com/plotsquared/core/command/Move.java @@ -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 execute(PlotPlayer player, String[] args, RunnableVal3 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); diff --git a/Core/src/main/java/com/plotsquared/core/command/Music.java b/Core/src/main/java/com/plotsquared/core/command/Music.java index 91b756a81..e3ee4afeb 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Music.java +++ b/Core/src/main/java/com/plotsquared/core/command/Music.java @@ -25,6 +25,7 @@ */ package com.plotsquared.core.command; +import com.google.inject.Inject; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.events.PlotFlagAddEvent; import com.plotsquared.core.events.PlotFlagRemoveEvent; @@ -36,7 +37,9 @@ import com.plotsquared.core.plot.PlotInventory; import com.plotsquared.core.plot.PlotItemStack; import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.implementations.MusicFlag; +import com.plotsquared.core.util.InventoryUtil; import com.sk89q.worldedit.world.item.ItemTypes; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; @@ -55,6 +58,12 @@ public class Music extends SubCommand { "music_disc_far", "music_disc_mall", "music_disc_mellohi", "music_disc_stal", "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait"); + private final InventoryUtil inventoryUtil; + + @Inject public Music(@Nullable final InventoryUtil inventoryUtil) { + this.inventoryUtil = inventoryUtil; + } + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); final Plot plot = location.getPlotAbs(); @@ -65,7 +74,7 @@ public class Music extends SubCommand { sendMessage(player, Captions.NO_PLOT_PERMS); return true; } - PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { + PlotInventory inv = new PlotInventory(this.inventoryUtil, player, 2, "Plot Jukebox") { @Override public boolean onClick(int index) { PlotItemStack item = getItem(index); if (item == null) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Owner.java b/Core/src/main/java/com/plotsquared/core/command/Owner.java index f19790dc5..c4b0938fb 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Owner.java +++ b/Core/src/main/java/com/plotsquared/core/command/Owner.java @@ -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; @@ -33,9 +34,11 @@ import com.plotsquared.core.events.PlotUnlinkEvent; import com.plotsquared.core.events.Result; 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.task.TaskManager; +import javax.annotation.Nonnull; import java.util.Set; import java.util.UUID; @@ -52,6 +55,12 @@ import java.util.function.Consumer; confirmation = true) public class Owner extends SetCommand { + private final EventDispatcher eventDispatcher; + + @Inject public Owner(@Nonnull final EventDispatcher eventDispatcher) { + this.eventDispatcher = eventDispatcher; + } + @Override public boolean set(final PlotPlayer player, final Plot plot, String value) { if (value == null || value.isEmpty()) { Captions.SET_OWNER_MISSING_PLAYER.send(player); @@ -65,9 +74,8 @@ public class Owner extends SetCommand { Captions.INVALID_PLAYER.send(player, value); return; } - PlotChangeOwnerEvent event = PlotSquared.get().getEventDispatcher() - .callOwnerChange(player, plot, plot.hasOwner() ? plot.getOwnerAbs() : null, uuid, - plot.hasOwner()); + PlotChangeOwnerEvent event = this.eventDispatcher.callOwnerChange(player, plot, plot.hasOwner() ? plot.getOwnerAbs() : null, uuid, + plot.hasOwner()); if (event.getEventResult() == Result.DENY) { sendMessage(player, Captions.EVENT_DENIED, "Owner change"); return; @@ -80,8 +88,7 @@ public class Owner extends SetCommand { true)) { return; } - PlotUnlinkEvent unlinkEvent = PlotSquared.get().getEventDispatcher() - .callUnlink(plot.getArea(), plot, false, false, PlotUnlinkEvent.REASON.NEW_OWNER); + PlotUnlinkEvent unlinkEvent = this.eventDispatcher.callUnlink(plot.getArea(), plot, false, false, PlotUnlinkEvent.REASON.NEW_OWNER); if (unlinkEvent.getEventResult() == Result.DENY) { sendMessage(player, Captions.EVENT_DENIED, "Unlink on owner change"); return; @@ -95,7 +102,7 @@ public class Owner extends SetCommand { MainUtil.sendMessage(player, Captions.SET_OWNER); return; } - final PlotPlayer other = PlotSquared.imp().getPlayerManager().getPlayerIfExists(uuid); + final PlotPlayer other = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); if (plot.isOwner(uuid)) { Captions.ALREADY_OWNER.send(player, MainUtil.getName(uuid)); return; diff --git a/Core/src/main/java/com/plotsquared/core/command/PluginCmd.java b/Core/src/main/java/com/plotsquared/core/command/PluginCmd.java index b0bf24d40..60925ccbd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/PluginCmd.java +++ b/Core/src/main/java/com/plotsquared/core/command/PluginCmd.java @@ -40,9 +40,9 @@ import com.plotsquared.core.util.task.TaskManager; public class PluginCmd extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - TaskManager.IMP.taskAsync(() -> { + TaskManager.getImplementation().taskAsync(() -> { MainUtil.sendMessage(player, String.format( - "$2>> $1&l" + PlotSquared.imp().getPluginName() + " $2($1Version$2: $1%s$2)", + "$2>> $1&l" + PlotSquared.platform().getPluginName() + " $2($1Version$2: $1%s$2)", PlotSquared.get().getVersion())); MainUtil.sendMessage(player, "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev $2& $1dordsor21 $2& $1NotMyFault $2& $1SirYwell"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Purge.java b/Core/src/main/java/com/plotsquared/core/command/Purge.java index 7056bd836..4b51144b1 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Purge.java +++ b/Core/src/main/java/com/plotsquared/core/command/Purge.java @@ -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; @@ -34,10 +35,12 @@ 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.StringMan; import com.plotsquared.core.util.task.TaskManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; import java.util.HashMap; import java.util.HashSet; @@ -57,6 +60,15 @@ public class Purge extends SubCommand { private static final Logger logger = LoggerFactory.getLogger("P2/" + Purge.class.getSimpleName()); + private final PlotAreaManager plotAreaManager; + private final PlotListener plotListener; + + @Inject public Purge(@Nonnull final PlotAreaManager plotAreaManager, + @Nonnull final PlotListener plotListener) { + this.plotAreaManager = plotAreaManager; + this.plotListener = plotListener; + } + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { Captions.COMMAND_SYNTAX.send(player, getUsage()); @@ -82,7 +94,7 @@ public class Purge extends SubCommand { break; case "area": case "a": - area = PlotSquared.get().getPlotAreaByString(split[1]); + area = this.plotAreaManager.getPlotAreaByString(split[1]); if (area == null) { Captions.NOT_VALID_PLOT_WORLD.send(player, split[1]); return false; @@ -199,7 +211,7 @@ public class Purge extends SubCommand { } plot.getArea().removePlot(plot.getId()); for (PlotPlayer pp : plot.getPlayersInPlot()) { - PlotListener.plotEntry(pp, plot); + Purge.this.plotListener.plotEntry(pp, plot); } } catch (NullPointerException e) { logger.error("[P2] NullPointer during purge detected. This is likely" diff --git a/Core/src/main/java/com/plotsquared/core/command/Rate.java b/Core/src/main/java/com/plotsquared/core/command/Rate.java index 23affc37d..64f21a381 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Rate.java +++ b/Core/src/main/java/com/plotsquared/core/command/Rate.java @@ -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; @@ -37,10 +38,13 @@ import com.plotsquared.core.plot.PlotInventory; import com.plotsquared.core.plot.PlotItemStack; 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.InventoryUtil; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.task.TaskManager; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; @@ -56,6 +60,15 @@ import java.util.UUID; requiredType = RequiredType.PLAYER) public class Rate extends SubCommand { + private final EventDispatcher eventDispatcher; + private final InventoryUtil inventoryUtil; + + @Inject public Rate(@Nonnull final EventDispatcher eventDispatcher, + @Nonnull final InventoryUtil inventoryUtil) { + this.eventDispatcher = eventDispatcher; + this.inventoryUtil = inventoryUtil; + } + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { switch (args[0].toLowerCase()) { @@ -135,13 +148,13 @@ public class Rate extends SubCommand { final MutableInt index = new MutableInt(0); final MutableInt rating = new MutableInt(0); String title = Settings.Ratings.CATEGORIES.get(0); - PlotInventory inventory = new PlotInventory(player, 1, title) { + PlotInventory inventory = new PlotInventory(inventoryUtil, player, 1, title) { @Override public boolean onClick(int i) { rating.add((i + 1) * Math.pow(10, index.getValue())); index.increment(); if (index.getValue() >= Settings.Ratings.CATEGORIES.size()) { int rV = rating.getValue(); - PlotRateEvent event = PlotSquared.get().getEventDispatcher() + PlotRateEvent event = Rate.this.eventDispatcher .callRating(this.player, plot, new Rating(rV)); if (event.getRating() != null) { plot.addRating(this.player.getUUID(), event.getRating()); @@ -211,7 +224,7 @@ public class Rate extends SubCommand { return; } 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()); sendMessage(player, Captions.RATING_APPLIED, plot.getId().toString()); diff --git a/Core/src/main/java/com/plotsquared/core/command/RegenAllRoads.java b/Core/src/main/java/com/plotsquared/core/command/RegenAllRoads.java index 69d0022f6..e159e85e7 100644 --- a/Core/src/main/java/com/plotsquared/core/command/RegenAllRoads.java +++ b/Core/src/main/java/com/plotsquared/core/command/RegenAllRoads.java @@ -25,14 +25,16 @@ */ 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.generator.HybridPlotManager; import com.plotsquared.core.generator.HybridUtils; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.MainUtil; +import javax.annotation.Nonnull; @CommandDeclaration(command = "regenallroads", description = "Regenerate all roads in the map using the set road schematic", @@ -43,6 +45,15 @@ import com.plotsquared.core.util.MainUtil; permission = "plots.regenallroads") public class RegenAllRoads extends SubCommand { + private final PlotAreaManager plotAreaManager; + private final HybridUtils hybridUtils; + + @Inject public RegenAllRoads(@Nonnull final PlotAreaManager plotAreaManager, + @Nonnull final HybridUtils hybridUtils) { + this.plotAreaManager = plotAreaManager; + this.hybridUtils = hybridUtils; + } + @Override public boolean onCommand(PlotPlayer player, String[] args) { int height = 0; if (args.length == 2) { @@ -59,7 +70,7 @@ public class RegenAllRoads extends SubCommand { "/plot regenallroads [height]"); return false; } - PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); + PlotArea area = this.plotAreaManager.getPlotAreaByString(args[0]); if (area == null) { Captions.NOT_VALID_PLOT_WORLD.send(player, args[0]); return false; @@ -77,7 +88,7 @@ public class RegenAllRoads extends SubCommand { "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); //MainUtil.sendMessage(player, "&6Potential chunks to update: &7" + (chunks.size() * 1024)); //MainUtil.sendMessage(player, "&6Estimated time: &7" + chunks.size() + " seconds"); - boolean result = HybridUtils.manager.scheduleRoadUpdate(area, height); + boolean result = this.hybridUtils.scheduleRoadUpdate(area, height); if (!result) { MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); diff --git a/Core/src/main/java/com/plotsquared/core/command/Reload.java b/Core/src/main/java/com/plotsquared/core/command/Reload.java index 0b8f4b6fe..72ec89596 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Reload.java +++ b/Core/src/main/java/com/plotsquared/core/command/Reload.java @@ -25,15 +25,21 @@ */ 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.MemorySection; import com.plotsquared.core.configuration.file.YamlConfiguration; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotAreaType; +import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.MainUtil; +import javax.annotation.Nonnull; +import java.io.File; import java.io.IOException; import java.util.Objects; @@ -45,14 +51,26 @@ import java.util.Objects; category = CommandCategory.ADMINISTRATION) public class Reload extends SubCommand { + private final PlotAreaManager plotAreaManager; + private final YamlConfiguration worldConfiguration; + private final File worldFile; + + @Inject public Reload(@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 boolean onCommand(PlotPlayer player, String[] args) { try { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. PlotSquared.get().setupConfigs(); Captions.load(PlotSquared.get().translationFile); - PlotSquared.get().forEachPlotArea(area -> { - ConfigurationSection worldSection = PlotSquared.get().worlds + this.plotAreaManager.forEachPlotArea(area -> { + ConfigurationSection worldSection = this.worldConfiguration .getConfigurationSection("worlds." + area.getWorldName()); if (worldSection == null) { return; @@ -98,7 +116,7 @@ public class Reload extends SubCommand { area.loadDefaultConfiguration(clone); } }); - PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); + this.worldConfiguration.save(this.worldFile); MainUtil.sendMessage(player, Captions.RELOADED_CONFIGS); } catch (IOException e) { e.printStackTrace(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Remove.java b/Core/src/main/java/com/plotsquared/core/command/Remove.java index 871bd2b60..b20a4da3a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Remove.java +++ b/Core/src/main/java/com/plotsquared/core/command/Remove.java @@ -25,15 +25,17 @@ */ 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.database.DBFunc; import com.plotsquared.core.location.Location; 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 javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; @@ -49,8 +51,11 @@ import java.util.concurrent.TimeoutException; permission = "plots.remove") public class Remove extends SubCommand { - public Remove() { + private final EventDispatcher eventDispatcher; + + @Inject public Remove(@Nonnull final EventDispatcher eventDispatcher) { super(Argument.PlayerName); + this.eventDispatcher = eventDispatcher; } @Override public boolean onCommand(PlotPlayer player, String[] args) { @@ -81,34 +86,28 @@ public class Remove extends SubCommand { for (UUID uuid : uuids) { if (plot.getTrusted().contains(uuid)) { if (plot.removeTrusted(uuid)) { - PlotSquared.get().getEventDispatcher() - .callTrusted(player, plot, uuid, false); + this.eventDispatcher.callTrusted(player, plot, uuid, false); count++; } } else if (plot.getMembers().contains(uuid)) { if (plot.removeMember(uuid)) { - PlotSquared.get().getEventDispatcher() - .callMember(player, plot, uuid, false); + this.eventDispatcher.callMember(player, plot, uuid, false); count++; } } else if (plot.getDenied().contains(uuid)) { if (plot.removeDenied(uuid)) { - PlotSquared.get().getEventDispatcher() - .callDenied(player, plot, uuid, false); + this.eventDispatcher.callDenied(player, plot, uuid, false); count++; } } else if (uuid == DBFunc.EVERYONE) { if (plot.removeTrusted(uuid)) { - PlotSquared.get().getEventDispatcher() - .callTrusted(player, plot, uuid, false); + this.eventDispatcher.callTrusted(player, plot, uuid, false); count++; } else if (plot.removeMember(uuid)) { - PlotSquared.get().getEventDispatcher() - .callMember(player, plot, uuid, false); + this.eventDispatcher.callMember(player, plot, uuid, false); count++; } else if (plot.removeDenied(uuid)) { - PlotSquared.get().getEventDispatcher() - .callDenied(player, plot, uuid, false); + this.eventDispatcher.callDenied(player, plot, uuid, false); count++; } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Save.java b/Core/src/main/java/com/plotsquared/core/command/Save.java index 480167576..3c814c655 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Save.java +++ b/Core/src/main/java/com/plotsquared/core/command/Save.java @@ -25,18 +25,20 @@ */ 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.PlotId; +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 com.sk89q.jnbt.CompoundTag; +import javax.annotation.Nonnull; import java.net.URL; import java.util.List; @@ -49,9 +51,18 @@ import java.util.UUID; permission = "plots.save") public class Save 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 Save(@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(); @@ -72,20 +83,20 @@ public class Save extends SubCommand { return false; } plot.addRunning(); - SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { + this.schematicHandler.getCompoundTag(plot, new RunnableVal() { @Override public void run(final CompoundTag value) { TaskManager.runTaskAsync(() -> { String time = (System.currentTimeMillis() / 1000) + ""; Location[] corners = plot.getCorners(); - corners[0].setY(0); - corners[1].setY(255); + corners[0] = corners[0].withY(0); + corners[1] = corners[1].withY(255); int size = (corners[1].getX() - corners[0].getX()) + 1; PlotId id = plot.getId(); String world1 = plot.getArea().toString().replaceAll(";", "-") .replaceAll("[^A-Za-z0-9]", ""); final String file = time + '_' + world1 + '_' + id.x + '_' + id.y + '_' + size; UUID uuid = player.getUUID(); - SchematicHandler.manager.upload(value, uuid, file, new RunnableVal() { + schematicHandler.upload(value, uuid, file, new RunnableVal() { @Override public void run(URL url) { plot.removeRunning(); if (url == null) { diff --git a/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java b/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java index 66e4a0662..131549d76 100644 --- a/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java +++ b/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java @@ -26,7 +26,7 @@ package com.plotsquared.core.command; import com.google.common.collect.Lists; -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.location.Location; @@ -35,12 +35,14 @@ import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; 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.StringMan; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; +import javax.annotation.Nonnull; import java.net.URL; import java.util.ArrayList; @@ -55,8 +57,16 @@ import java.util.UUID; usage = "/plot schematic ") public class SchematicCmd extends SubCommand { + private final PlotAreaManager plotAreaManager; + private final SchematicHandler schematicHandler; private boolean running = false; + @Inject public SchematicCmd(@Nonnull final PlotAreaManager plotAreaManager, + @Nonnull final SchematicHandler schematicHandler) { + this.plotAreaManager = plotAreaManager; + this.schematicHandler = schematicHandler; + } + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { sendMessage(player, Captions.SCHEMATIC_MISSING_ARG); @@ -105,7 +115,7 @@ public class SchematicCmd extends SubCommand { UUID uuid = UUID.fromString(location.substring(4)); URL base = new URL(Settings.Web.URL); URL url = new URL(base, "uploads/" + uuid + ".schematic"); - schematic = SchematicHandler.manager.getSchematic(url); + schematic = this.schematicHandler.getSchematic(url); } catch (Exception e) { e.printStackTrace(); sendMessage(player, Captions.SCHEMATIC_INVALID, @@ -115,7 +125,7 @@ public class SchematicCmd extends SubCommand { } } else { try { - schematic = SchematicHandler.manager.getSchematic(location); + schematic = this.schematicHandler.getSchematic(location); } catch (SchematicHandler.UnsupportedFormatException e) { e.printStackTrace(); } @@ -126,8 +136,7 @@ public class SchematicCmd extends SubCommand { "non-existent or not in gzip format"); return; } - SchematicHandler.manager - .paste(schematic, plot, 0, 1, 0, false, new RunnableVal() { + this.schematicHandler.paste(schematic, plot, 0, 1, 0, false, new RunnableVal() { @Override public void run(Boolean value) { SchematicCmd.this.running = false; if (value) { @@ -150,7 +159,7 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_WORLD_ARGS); return false; } - PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); + PlotArea area = this.plotAreaManager.getPlotAreaByString(args[1]); if (area == null) { Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; @@ -160,7 +169,7 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_WORLD); return false; } - boolean result = SchematicHandler.manager.exportAll(plots, null, null, + boolean result = this.schematicHandler.exportAll(plots, null, null, () -> MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_FINISHED)); if (!result) { MainUtil.sendMessage(player, Captions.TASK_IN_PROCESS); @@ -198,7 +207,7 @@ public class SchematicCmd extends SubCommand { return false; } ArrayList plots = Lists.newArrayList(plot); - boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> { + boolean result = this.schematicHandler.exportAll(plots, null, null, () -> { MainUtil.sendMessage(player, Captions.SCHEMATIC_EXPORTALL_SINGLE_FINISHED); SchematicCmd.this.running = false; }); @@ -215,8 +224,7 @@ public class SchematicCmd extends SubCommand { Captions.PERMISSION_SCHEMATIC_LIST); return false; } - final String string = - StringMan.join(SchematicHandler.manager.getSchematicNames(), "$2, $1"); + final String string = StringMan.join(this.schematicHandler.getSchematicNames(), "$2, $1"); Captions.SCHEMATIC_LIST.send(player, string); } break; diff --git a/Core/src/main/java/com/plotsquared/core/command/Set.java b/Core/src/main/java/com/plotsquared/core/command/Set.java index ec75fd9eb..743433ad2 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Set.java +++ b/Core/src/main/java/com/plotsquared/core/command/Set.java @@ -25,12 +25,14 @@ */ package com.plotsquared.core.command; +import com.google.inject.Inject; import com.plotsquared.core.backup.BackupManager; import com.plotsquared.core.configuration.CaptionUtility; 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.PlotArea; import com.plotsquared.core.plot.PlotManager; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.util.MainUtil; @@ -43,6 +45,7 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.block.BlockCategory; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; @@ -66,8 +69,13 @@ public class Set extends SubCommand { public static final String[] aliases = new String[] {"b", "w", "wf", "a", "h"}; private final SetCommand component; + private final WorldUtil worldUtil; + private final GlobalBlockQueue blockQueue; - public Set() { + @Inject public Set(@Nonnull final WorldUtil worldUtil, + @Nonnull final GlobalBlockQueue blockQueue) { + this.worldUtil = worldUtil; + this.blockQueue = blockQueue; this.component = new SetCommand() { @Override public String getId() { @@ -75,7 +83,12 @@ public class Set extends SubCommand { } @Override public boolean set(PlotPlayer player, final Plot plot, String value) { - PlotManager manager = player.getLocation().getPlotManager(); + final PlotArea plotArea = player.getLocation().getPlotArea(); + if (plotArea == null) { + return false; + } + final PlotManager manager = plotArea.getPlotManager(); + String[] components = manager.getPlotComponents(plot.getId()); String[] args = value.split(" "); @@ -85,7 +98,7 @@ public class Set extends SubCommand { final List forbiddenTypes = new ArrayList<>(Settings.General.INVALID_BLOCKS); if (Settings.Enabled_Components.CHUNK_PROCESSOR) { - forbiddenTypes.addAll(WorldUtil.IMP.getTileEntityTypes().stream().map( + forbiddenTypes.addAll(worldUtil.getTileEntityTypes().stream().map( BlockType::getName).collect(Collectors.toList())); } @@ -148,7 +161,7 @@ public class Set extends SubCommand { current.setComponent(component, pattern); } MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - GlobalBlockQueue.IMP.addEmptyTask(plot::removeRunning); + blockQueue.addEmptyTask(plot::removeRunning); }); return true; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Setup.java b/Core/src/main/java/com/plotsquared/core/command/Setup.java index bdcd20697..cf412656a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Setup.java +++ b/Core/src/main/java/com/plotsquared/core/command/Setup.java @@ -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.generator.GeneratorWrapper; @@ -33,6 +34,7 @@ import com.plotsquared.core.setup.SetupProcess; import com.plotsquared.core.setup.SetupStep; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.SetupUtils; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; @@ -48,11 +50,17 @@ import java.util.Map.Entry; category = CommandCategory.ADMINISTRATION) public class Setup extends SubCommand { + private final SetupUtils setupUtils; + + @Inject public Setup(@Nonnull final SetupUtils setupUtils) { + this.setupUtils = setupUtils; + } + public void displayGenerators(PlotPlayer player) { StringBuilder message = new StringBuilder(); message.append("&6What generator do you want?"); for (Entry> entry : SetupUtils.generators.entrySet()) { - if (entry.getKey().equals(PlotSquared.imp().getPluginName())) { + if (entry.getKey().equals(PlotSquared.platform().getPluginName())) { message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)"); } else if (entry.getValue().isFull()) { message.append("\n&8 - &7").append(entry.getKey()).append(" (Plot Generator)"); @@ -72,7 +80,7 @@ public class Setup extends SubCommand { } process = new SetupProcess(); player.setMeta("setup", process); - SetupUtils.manager.updateGenerators(); + this.setupUtils.updateGenerators(); SetupStep step = process.getCurrentStep(); step.announce(player); displayGenerators(player); diff --git a/Core/src/main/java/com/plotsquared/core/command/Target.java b/Core/src/main/java/com/plotsquared/core/command/Target.java index a70ac3451..410aca635 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Target.java +++ b/Core/src/main/java/com/plotsquared/core/command/Target.java @@ -25,13 +25,13 @@ */ package com.plotsquared.core.command; -import com.plotsquared.core.PlotSquared; 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.util.MainUtil; import com.plotsquared.core.util.StringMan; +import com.plotsquared.core.util.query.PlotQuery; @CommandDeclaration(command = "target", usage = "/plot target <|nearest>", @@ -54,7 +54,7 @@ public class Target extends SubCommand { Plot target = null; if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) { int distance = Integer.MAX_VALUE; - for (Plot plot : PlotSquared.get().getPlots(location.getWorld())) { + for (Plot plot : PlotQuery.newQuery().inWorld(location.getWorldName()).asCollection()) { double current = plot.getCenterSynchronous().getEuclideanDistanceSquared(location); if (current < distance) { distance = (int) current; diff --git a/Core/src/main/java/com/plotsquared/core/command/Template.java b/Core/src/main/java/com/plotsquared/core/command/Template.java index 02bc7af4d..5e90d5a90 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Template.java +++ b/Core/src/main/java/com/plotsquared/core/command/Template.java @@ -25,7 +25,10 @@ */ 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.ConfigurationNode; import com.plotsquared.core.configuration.ConfigurationSection; @@ -36,6 +39,7 @@ import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.setup.PlotAreaBuilder; import com.plotsquared.core.setup.SettingsNodesWrapper; @@ -44,6 +48,7 @@ import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.SetupUtils; import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.task.TaskManager; +import javax.annotation.Nonnull; import java.io.File; import java.io.FileInputStream; @@ -61,14 +66,35 @@ import java.util.zip.ZipOutputStream; category = CommandCategory.ADMINISTRATION) public class Template extends SubCommand { + private final PlotAreaManager plotAreaManager; + private final YamlConfiguration worldConfiguration; + private final File worldFile; + private final SetupUtils setupUtils; + private final GlobalBlockQueue globalBlockQueue; + private final WorldUtil worldUtil; + + @Inject public Template(@Nonnull final PlotAreaManager plotAreaManager, + @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, + @WorldFile @Nonnull final File worldFile, + @Nonnull final SetupUtils setupUtils, + @Nonnull final GlobalBlockQueue globalBlockQueue, + @Nonnull final WorldUtil worldUtil) { + this.plotAreaManager = plotAreaManager; + this.worldConfiguration = worldConfiguration; + this.worldFile = worldFile; + this.setupUtils = setupUtils; + this.globalBlockQueue = globalBlockQueue; + this.worldUtil = worldUtil; + } + public static boolean extractAllFiles(String world, String template) { try { File folder = - MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), Settings.Paths.TEMPLATES); + MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES); if (!folder.exists()) { return false; } - File output = PlotSquared.get().IMP.getDirectory(); + File output = PlotSquared.platform().getDirectory(); if (!output.exists()) { output.mkdirs(); } @@ -105,10 +131,9 @@ public class Template extends SubCommand { } public static byte[] getBytes(PlotArea plotArea) { - ConfigurationSection section = - PlotSquared.get().worlds.getConfigurationSection("worlds." + plotArea.getWorldName()); + ConfigurationSection section = PlotSquared.get().getWorldConfiguration().getConfigurationSection("worlds." + plotArea.getWorldName()); YamlConfiguration config = new YamlConfiguration(); - String generator = SetupUtils.manager.getGenerator(plotArea); + String generator = PlotSquared.platform().getSetupUtils().getGenerator(plotArea); if (generator != null) { config.set("generator.plugin", generator); } @@ -120,7 +145,7 @@ public class Template extends SubCommand { public static void zipAll(String world, Set files) throws IOException { File output = - MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), Settings.Paths.TEMPLATES); + MainUtil.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.TEMPLATES); output.mkdirs(); try (FileOutputStream fos = new FileOutputStream( output + File.separator + world + ".template"); @@ -159,7 +184,7 @@ public class Template extends SubCommand { "/plot template import