Merge branch 'v6' into feature/v6/json

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.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) {

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -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;

View File

@ -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");

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -34,8 +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;
@ -53,6 +58,17 @@ import java.util.concurrent.atomic.AtomicBoolean;
confirmation = true)
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());
@ -78,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;
@ -170,7 +186,9 @@ public class Purge extends SubCommand {
"/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)";
boolean finalClear = clear;
Runnable run = () -> {
PlotSquared.debug("Calculating plots to purge, please wait...");
if (Settings.DEBUG) {
logger.info("[P2] Calculating plots to purge, please wait...");
}
HashSet<Integer> ids = new HashSet<>();
Iterator<Plot> iterator = toDelete.iterator();
AtomicBoolean cleared = new AtomicBoolean(true);
@ -183,22 +201,21 @@ public class Purge extends SubCommand {
try {
ids.add(plot.temp);
if (finalClear) {
plot.clear(false, true, () -> PlotSquared
.debug("Plot " + plot.getId() + " cleared by purge."));
plot.clear(false, true, () -> {
if (Settings.DEBUG) {
logger.info("[P2] Plot {} cleared by purge", plot.getId());
}
});
} else {
plot.removeSign();
}
plot.getArea().removePlot(plot.getId());
for (PlotPlayer pp : plot.getPlayersInPlot()) {
PlotListener.plotEntry(pp, plot);
for (PlotPlayer<?> pp : plot.getPlayersInPlot()) {
Purge.this.plotListener.plotEntry(pp, plot);
}
} catch (NullPointerException e) {
PlotSquared.log(
"NullPointer during purge detected. This is likely because you are "
+ "deleting a world that has been removed.");
if (Settings.DEBUG) {
e.printStackTrace();
}
logger.error("[P2] NullPointer during purge detected. This is likely"
+ " because you are deleting a world that has been removed", e);
}
}
cleared.set(true);

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.Settings;
@ -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());

View File

@ -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 <world> [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?)");

View File

@ -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();

View File

@ -25,15 +25,17 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.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++;
}
}

View File

@ -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<CompoundTag>() {
this.schematicHandler.getCompoundTag(plot, new RunnableVal<CompoundTag>() {
@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<URL>() {
schematicHandler.upload(value, uuid, file, new RunnableVal<URL>() {
@Override public void run(URL url) {
plot.removeRunning();
if (url == null) {

View File

@ -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 <save|saveall|paste>")
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<Boolean>() {
this.schematicHandler.paste(schematic, plot, 0, 1, 0, false, new RunnableVal<Boolean>() {
@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<Plot> 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;

View File

@ -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<String> 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;
}

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.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<String, GeneratorWrapper<?>> 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);

View File

@ -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 <<plot>|nearest>",
@ -42,7 +42,7 @@ import com.plotsquared.core.util.StringMan;
public class Target extends SubCommand {
public Target() {
super(Argument.PlotID);
super();
}
@Override public boolean onCommand(PlotPlayer<?> player, String[] args) {
@ -51,10 +51,14 @@ public class Target extends SubCommand {
MainUtil.sendMessage(player, Captions.NOT_IN_PLOT_WORLD);
return false;
}
if (args.length == 0) {
MainUtil.sendMessage(player, this.getUsage());
return false;
}
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;

View File

@ -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<FileBytes> 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 <world> <template>");
return false;
}
if (PlotSquared.get().hasPlotArea(world)) {
if (this.plotAreaManager.hasPlotArea(world)) {
MainUtil.sendMessage(player, Captions.SETUP_WORLD_TAKEN, world);
return false;
}
@ -169,20 +194,20 @@ public class Template extends SubCommand {
.sendMessage(player, "&cInvalid template file: " + args[2] + ".template");
return false;
}
File worldFile = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
File worldFile = MainUtil.getFile(PlotSquared.platform().getDirectory(),
Settings.Paths.TEMPLATES + File.separator + "tmp-data.yml");
YamlConfiguration worldConfig = YamlConfiguration.loadConfiguration(worldFile);
PlotSquared.get().worlds.set("worlds." + world, worldConfig.get(""));
this.worldConfiguration.set("worlds." + world, worldConfig.get(""));
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
PlotSquared.get().worlds.load(PlotSquared.get().worldsFile);
this.worldConfiguration.save(this.worldFile);
this.worldConfiguration.load(this.worldFile);
} catch (InvalidConfigurationException | IOException e) {
e.printStackTrace();
}
String manager =
worldConfig.getString("generator.plugin", PlotSquared.imp().getPluginName());
worldConfig.getString("generator.plugin", PlotSquared.platform().getPluginName());
String generator = worldConfig.getString("generator.init", manager);
PlotAreaBuilder builder = new PlotAreaBuilder()
PlotAreaBuilder builder = PlotAreaBuilder.newBuilder()
.plotAreaType(MainUtil.getType(worldConfig))
.terrainType(MainUtil.getTerrain(worldConfig))
.plotManager(manager)
@ -190,10 +215,10 @@ public class Template extends SubCommand {
.settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null))
.worldName(world);
SetupUtils.manager.setupWorld(builder);
GlobalBlockQueue.IMP.addEmptyTask(() -> {
this.setupUtils.setupWorld(builder);
this.globalBlockQueue.addEmptyTask(() -> {
MainUtil.sendMessage(player, "Done!");
player.teleport(WorldUtil.IMP.getSpawn(world), TeleportCause.COMMAND);
player.teleport(this.worldUtil.getSpawn(world), TeleportCause.COMMAND);
});
return true;
}
@ -203,7 +228,7 @@ public class Template extends SubCommand {
"/plot template export <world>");
return false;
}
final PlotArea area = PlotSquared.get().getPlotAreaByString(world);
final PlotArea area = this.plotAreaManager.getPlotAreaByString(world);
if (area == null) {
MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD);
return false;

View File

@ -25,33 +25,33 @@
*/
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.location.Location;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.expiration.ExpireManager;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.RegionUtil;
import com.plotsquared.core.util.WorldUtil;
import com.plotsquared.core.util.query.PlotQuery;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.TaskManager;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@CommandDeclaration(command = "trim",
@ -62,58 +62,22 @@ import java.util.Set;
category = CommandCategory.ADMINISTRATION)
public class Trim extends SubCommand {
public static ArrayList<Plot> expired = null;
private static final Logger logger = LoggerFactory.getLogger("P2/" + Trim.class.getSimpleName());
private static volatile boolean TASK = false;
public static boolean getBulkRegions(final ArrayList<BlockVector2> empty, final String world,
final Runnable whenDone) {
if (Trim.TASK) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
String directory = world + File.separator + "region";
File folder = new File(PlotSquared.get().IMP.getWorldContainer(), directory);
File[] regionFiles = folder.listFiles();
for (File file : regionFiles) {
String name = file.getName();
if (name.endsWith("mca")) {
if (file.getTotalSpace() <= 8192) {
checkMca(name);
} else {
Path path = Paths.get(file.getPath());
try {
BasicFileAttributes attr =
Files.readAttributes(path, BasicFileAttributes.class);
long creation = attr.creationTime().toMillis();
long modification = file.lastModified();
long diff = Math.abs(creation - modification);
if (diff < 10000) {
checkMca(name);
}
} catch (IOException ignored) {
}
}
}
}
Trim.TASK = false;
TaskManager.runTaskAsync(whenDone);
}
private final PlotAreaManager plotAreaManager;
private final WorldUtil worldUtil;
private final GlobalBlockQueue blockQueue;
private final RegionManager regionManager;
private void checkMca(String name) {
try {
String[] split = name.split("\\.");
int x = Integer.parseInt(split[1]);
int z = Integer.parseInt(split[2]);
BlockVector2 loc = BlockVector2.at(x, z);
empty.add(loc);
} catch (NumberFormatException ignored) {
PlotSquared.debug("INVALID MCA: " + name);
}
}
});
Trim.TASK = true;
return true;
@Inject public Trim(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final WorldUtil worldUtil,
@Nonnull final GlobalBlockQueue blockQueue,
@Nonnull final RegionManager regionManager) {
this.plotAreaManager = plotAreaManager;
this.worldUtil = worldUtil;
this.blockQueue = blockQueue;
this.regionManager = regionManager;
}
/**
@ -129,11 +93,11 @@ public class Trim extends SubCommand {
return false;
}
MainUtil.sendMessage(null, "Collecting region data...");
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots(world));
final List<Plot> plots = PlotQuery.newQuery().inWorld(world).asList();
if (ExpireManager.IMP != null) {
plots.removeAll(ExpireManager.IMP.getPendingExpired());
}
result.value1 = new HashSet<>(RegionManager.manager.getChunkChunks(world));
result.value1 = new HashSet<>(PlotSquared.platform().getRegionManager().getChunkChunks(world));
result.value2 = new HashSet<>();
MainUtil.sendMessage(null, " - MCA #: " + result.value1.size());
MainUtil.sendMessage(null, " - CHUNKS: " + (result.value1.size() * 1024) + " (max)");
@ -165,7 +129,7 @@ public class Trim extends SubCommand {
return false;
}
final String world = args[0];
if (!WorldUtil.IMP.isWorld(world) || !PlotSquared.get().hasPlotArea(world)) {
if (!this.worldUtil.isWorld(world) || !this.plotAreaManager.hasPlotArea(world)) {
MainUtil.sendMessage(player, Captions.NOT_VALID_WORLD);
return false;
}
@ -179,14 +143,15 @@ public class Trim extends SubCommand {
@Override public void run(Set<BlockVector2> viable, final Set<BlockVector2> nonViable) {
Runnable regenTask;
if (regen) {
PlotSquared.log("Starting regen task:");
PlotSquared.log(" - This is a VERY slow command");
PlotSquared.log(" - It will say `Trim done!` when complete");
logger.info("[P2] Starting regen task");
logger.info("[P2] - This is a VERY slow command");
logger.info("[P2] - It will say 'Trim done!' when complete");
regenTask = new Runnable() {
@Override public void run() {
if (nonViable.isEmpty()) {
Trim.TASK = false;
player.sendMessage("Trim done!");
logger.info("[P2] Trim done!");
return;
}
Iterator<BlockVector2> iterator = nonViable.iterator();
@ -206,7 +171,7 @@ public class Trim extends SubCommand {
int bz = cbz << 4;
CuboidRegion region =
RegionUtil.createRegion(bx, bx + 511, bz, bz + 511);
for (Plot plot : PlotSquared.get().getPlots(world)) {
for (Plot plot : PlotQuery.newQuery().inWorld(world).asCollection()) {
Location bot = plot.getBottomAbs();
Location top = plot.getExtendedTopAbs();
CuboidRegion plotReg = RegionUtil
@ -223,8 +188,7 @@ public class Trim extends SubCommand {
}
}
}
final LocalBlockQueue queue =
GlobalBlockQueue.IMP.getNewQueue(world, false);
final LocalBlockQueue queue = blockQueue.getNewQueue(world, false);
TaskManager.objectTask(chunks, new RunnableVal<BlockVector2>() {
@Override public void run(BlockVector2 value) {
queue.regenChunk(value.getX(), value.getZ());
@ -238,7 +202,7 @@ public class Trim extends SubCommand {
player.sendMessage("Trim done!");
};
}
RegionManager.manager.deleteRegionFiles(world, viable, regenTask);
regionManager.deleteRegionFiles(world, viable, regenTask);
}
});

View File

@ -25,16 +25,18 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.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;
category = CommandCategory.SETTINGS)
public class Trust extends Command {
public Trust() {
private final EventDispatcher eventDispatcher;
@Inject public Trust(@Nonnull final EventDispatcher eventDispatcher) {
super(MainCommand.getInstance(), true);
this.eventDispatcher = eventDispatcher;
}
@Override
@ -119,7 +124,7 @@ public class Trust extends Command {
}
}
currentPlot.addTrusted(uuid);
PlotSquared.get().getEventDispatcher().callTrusted(player, currentPlot, uuid, true);
this.eventDispatcher.callTrusted(player, currentPlot, uuid, true);
MainUtil.sendMessage(player, Captions.TRUSTED_ADDED);
}
}, null);

View File

@ -25,17 +25,19 @@
*/
package com.plotsquared.core.command;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.events.PlotUnlinkEvent;
import com.plotsquared.core.events.Result;
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.StringMan;
import com.plotsquared.core.util.task.TaskManager;
import javax.annotation.Nonnull;
@CommandDeclaration(command = "unlink",
aliases = {"u", "unmerge"},
@ -46,6 +48,12 @@ import com.plotsquared.core.util.task.TaskManager;
confirmation = true)
public class Unlink extends SubCommand {
private final EventDispatcher eventDispatcher;
@Inject public Unlink(@Nonnull final EventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
@Override public boolean onCommand(final PlotPlayer<?> player, String[] args) {
Location location = player.getLocation();
final Plot plot = location.getPlotAbs();
@ -69,7 +77,7 @@ public class Unlink extends SubCommand {
createRoad = true;
}
PlotUnlinkEvent event = PlotSquared.get().getEventDispatcher()
PlotUnlinkEvent event = this.eventDispatcher
.callUnlink(plot.getArea(), plot, createRoad, createRoad,
PlotUnlinkEvent.REASON.PLAYER_COMMAND);
if (event.getEventResult() == Result.DENY) {

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.command;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.events.TeleportCause;
@ -32,6 +33,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.UntrustedVisitFlag;
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 +42,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;
@ -59,16 +61,19 @@ import java.util.concurrent.TimeoutException;
category = CommandCategory.TELEPORT)
public class Visit extends Command {
public Visit() {
private final PlotAreaManager plotAreaManager;
@Inject public Visit(@Nonnull final PlotAreaManager plotAreaManager) {
super(MainCommand.getInstance(), true);
this.plotAreaManager = plotAreaManager;
}
private void visit(@NotNull final PlotPlayer player, @NotNull final PlotQuery query, final PlotArea sortByArea,
private void visit(@Nonnull final PlotPlayer player, @Nonnull final PlotQuery query, final PlotArea sortByArea,
final RunnableVal3<Command, Runnable, Runnable> confirm, final RunnableVal2<Command, CommandResult> whenDone) {
this.visit(player, query, sortByArea, confirm, whenDone, 1);
}
private void visit(@NotNull final PlotPlayer player, @NotNull final PlotQuery query, final PlotArea sortByArea,
private void visit(@Nonnull final PlotPlayer player, @Nonnull final PlotQuery query, final PlotArea sortByArea,
final RunnableVal3<Command, Runnable, Runnable> confirm, final RunnableVal2<Command, CommandResult> whenDone, int page) {
// We get the query once,
// then we get it another time further on
@ -164,7 +169,7 @@ public class Visit extends Command {
// /p v <name> [page]
case 2:
if (page != Integer.MIN_VALUE || !MathMan.isInteger(args[1])) {
sortByArea = PlotSquared.get().getPlotAreaByString(args[1]);
sortByArea = this.plotAreaManager.getPlotAreaByString(args[1]);
if (sortByArea == null) {
Captions.NOT_VALID_NUMBER.send(player, "(1, ∞)");
Captions.COMMAND_SYNTAX.send(player, getUsage());
@ -198,7 +203,7 @@ public class Visit extends Command {
if (throwable instanceof TimeoutException) {
// The request timed out
MainUtil.sendMessage(player, Captions.FETCHING_PLAYERS_TIMEOUT);
} else if (uuid != null && !PlotSquared.get().hasPlot(uuid)) {
} else if (uuid != null && !PlotQuery.newQuery().ownedBy(uuid).anyMatch()) {
// It was a valid UUID but the player has no plots
MainUtil.sendMessage(player, Captions.PLAYER_NO_PLOTS);
} else if (uuid == null) {
@ -275,7 +280,7 @@ public class Visit extends Command {
}
private void completeAreas(final List<Command> commands, final String arg) {
for (final PlotArea area : PlotSquared.get().getPlotAreas()) {
for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) {
final String areaName = area.getWorldName() + ";" + area.getId();
if (!areaName.toLowerCase().startsWith(arg.toLowerCase())) {
continue;

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.configuration.serialization.SerializableAs;
import com.plotsquared.core.generator.ClassicPlotManagerComponent;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashMap;
@ -63,7 +63,7 @@ public class ComponentPreset implements ConfigurationSerializable {
this.icon = icon;
}
public static ComponentPreset deserialize(@NotNull final Map<String, Object> map) {
public static ComponentPreset deserialize(@Nonnull final Map<String, Object> map) {
final ClassicPlotManagerComponent classicPlotManagerComponent = ClassicPlotManagerComponent
.fromString(map.getOrDefault("component", "").toString()).orElseThrow(() ->
new IllegalArgumentException("The preset needs a valid target component"));

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.components;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.backup.BackupManager;
import com.plotsquared.core.command.MainCommand;
@ -36,14 +37,17 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotInventory;
import com.plotsquared.core.plot.PlotItemStack;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.InventoryUtil;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.PatternUtil;
import com.plotsquared.core.util.Permissions;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.world.item.ItemTypes;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
@ -57,11 +61,18 @@ import java.util.stream.Collectors;
public class ComponentPresetManager {
private static final Logger logger = LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName());
private final List<ComponentPreset> presets;
private final String guiName;
private final EconHandler econHandler;
private final InventoryUtil inventoryUtil;
public ComponentPresetManager() {
final File file = new File(Objects.requireNonNull(PlotSquared.imp()).getDirectory(), "components.yml");
@Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Nonnull final
InventoryUtil inventoryUtil) {
this.econHandler = econHandler;
this.inventoryUtil = inventoryUtil;
final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), "components.yml");
if (!file.exists()) {
boolean created = false;
try {
@ -70,7 +81,7 @@ public class ComponentPresetManager {
e.printStackTrace();
}
if (!created) {
PlotSquared.log(Captions.PREFIX + "Failed to create components.yml");
logger.error("[P2] Failed to create components.yml");
this.guiName = "&cInvalid!";
this.presets = new ArrayList<>();
return;
@ -86,8 +97,7 @@ public class ComponentPresetManager {
try {
yamlConfiguration.save(file);
} catch (IOException e) {
PlotSquared.log(Captions.PREFIX + "Failed to save default values to components.yml");
e.printStackTrace();
logger.error("[P2] Failed to save default values to components.yml", e);
}
}
this.guiName = yamlConfiguration.getString("title", "&6Plot Components");
@ -105,8 +115,7 @@ public class ComponentPresetManager {
try {
yamlConfiguration.save(file);
} catch (final IOException e) {
PlotSquared.log(Captions.PREFIX + "Failed to save default values to components.yml");
e.printStackTrace();
logger.error("[P2] Failed to save default values to components.yml", e);
}
this.presets = defaultPreset;
}
@ -144,7 +153,7 @@ public class ComponentPresetManager {
allowedPresets.add(componentPreset);
}
final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D);
final PlotInventory plotInventory = new PlotInventory(player, size, this.guiName) {
final PlotInventory plotInventory = new PlotInventory(this.inventoryUtil, player, size, this.guiName) {
@Override public boolean onClick(final int index) {
if (!player.getCurrentPlot().equals(plot)) {
return false;
@ -170,12 +179,12 @@ public class ComponentPresetManager {
return false;
}
if (componentPreset.getCost() > 0.0D && EconHandler.getEconHandler() != null && plot.getArea().useEconomy()) {
if (EconHandler.getEconHandler().getMoney(player) < componentPreset.getCost()) {
if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea().useEconomy()) {
if (econHandler.getMoney(player) < componentPreset.getCost()) {
Captions.PRESET_CANNOT_AFFORD.send(player);
return false;
} else {
EconHandler.getEconHandler().withdrawMoney(player, componentPreset.getCost());
econHandler.withdrawMoney(player, componentPreset.getCost());
Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + "");
}
}
@ -186,7 +195,7 @@ public class ComponentPresetManager {
current.setComponent(componentPreset.getComponent().name(), pattern);
}
MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT);
GlobalBlockQueue.IMP.addEmptyTask(plot::removeRunning);
PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(plot::removeRunning);
});
return false;
}
@ -196,7 +205,7 @@ public class ComponentPresetManager {
for (int i = 0; i < allowedPresets.size(); i++) {
final ComponentPreset preset = allowedPresets.get(i);
final List<String> lore = new ArrayList<>();
if (preset.getCost() > 0 && EconHandler.getEconHandler() != null && plot.getArea().useEconomy()){
if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()){
lore.add(Captions.PRESET_LORE_COST.getTranslated().replace("%cost%",
String.format("%.2f", preset.getCost())));
}

View File

@ -25,10 +25,11 @@
*/
package com.plotsquared.core.configuration;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings.Enabled_Components;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.util.StringMan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.PrintWriter;
@ -46,6 +47,8 @@ import java.util.Map;
public class Config {
private static final Logger logger = LoggerFactory.getLogger("P2/" + Config.class.getSimpleName());
/**
* Get the value for a node<br>
* Probably throws some error if you try to get a non existent key
@ -68,7 +71,6 @@ public class Config {
}
}
}
PlotSquared.debug("Failed to get config option: " + key);
return null;
}
@ -95,15 +97,13 @@ public class Config {
}
field.set(instance, value);
return;
} catch (Throwable e) {
PlotSquared.debug(
"Invalid configuration value: " + key + ": " + value + " in " + root
.getSimpleName());
} catch (final Throwable e) {
logger.error("[P2] Invalid configuration value '{}: {}' in {}", key, value, root.getSimpleName());
e.printStackTrace();
}
}
}
PlotSquared.debug("Failed to set config option: " + key + ": " + value + " | " + instance);
logger.error("[P2] Failed to set config option '{}: {}' | {}", key, value, instance);
}
public static boolean load(File file, Class<? extends Config> root) {
@ -288,10 +288,10 @@ public class Config {
Field field = instance.getClass().getField(toFieldName(split[split.length - 1]));
setAccessible(field);
return field;
} catch (Throwable e) {
PlotSquared.debug(
"Invalid config field: " + StringMan.join(split, ".") + " for " + toNodeName(
instance.getClass().getSimpleName()));
} catch (final Throwable e) {
logger.error("[P2] Invalid config field: {} for {}",
StringMan.join(split, "."), toNodeName(instance.getClass().getSimpleName()));
e.printStackTrace();
return null;
}
}

View File

@ -31,7 +31,9 @@ import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState;
import lombok.Getter;
import lombok.NonNull;
import javax.annotation.Nonnull;
/**
* Main Configuration Utility
@ -104,7 +106,7 @@ public class ConfigurationUtil {
@Getter private final String unknownValue;
UnknownBlockException(@NonNull final String unknownValue) {
UnknownBlockException(@Nonnull final String unknownValue) {
super(String.format("\"%s\" is not a valid block", unknownValue));
this.unknownValue = unknownValue;
}
@ -137,7 +139,7 @@ public class ConfigurationUtil {
@Getter private final BlockState unsafeBlock;
UnsafeBlockException(@NonNull final BlockState unsafeBlock) {
UnsafeBlockException(@Nonnull final BlockState unsafeBlock) {
super(String.format("%s is not a valid block", unsafeBlock));
this.unsafeBlock = unsafeBlock;
}

View File

@ -260,6 +260,16 @@ public class Settings extends Config {
@Comment("Whether or not automatic background caching should be enabled. It is HIGHLY recommended to keep this turned on."
+ " This should only be disabled if the server has a very large number of plots (>100k)")
public static boolean BACKGROUND_CACHING_ENABLED = true;
@Comment("Whether the PaperMC service is enabled")
public static boolean SERVICE_PAPER = true;
@Comment("Whether the LuckPerms service is enabled")
public static boolean SERVICE_LUCKPERMS = true;
@Comment("Whether the Bukkit service is enabled")
public static boolean SERVICE_BUKKIT = true;
@Comment("Whether the EssentialsX service is enabled")
public static boolean SERVICE_ESSENTIALSX = true;
@Comment("Whether the BungeePerms service is enabled")
public static boolean SERVICE_BUNGEE_PERMS = true;
}

View File

@ -25,10 +25,12 @@
*/
package com.plotsquared.core.configuration.file;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Configuration;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.InvalidConfigurationException;
import com.plotsquared.core.configuration.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
@ -45,6 +47,9 @@ import java.util.Map;
* Note that this implementation is not synchronized.
*/
public class YamlConfiguration extends FileConfiguration {
private static final Logger logger = LoggerFactory.getLogger("P2/" + YamlConfiguration.class.getSimpleName());
private static final String COMMENT_PREFIX = "# ";
private static final String BLANK_CONFIG = "{}\n";
private final DumperOptions yamlOptions = new DumperOptions();
@ -76,11 +81,13 @@ public class YamlConfiguration extends FileConfiguration {
dest = new File(file.getAbsolutePath() + "_broken_" + i++);
}
Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
PlotSquared.debug("&dCould not read: &7" + file);
PlotSquared.debug("&dRenamed to: &7" + dest.getName());
PlotSquared.debug("&c============ Full stacktrace ============");
ex.printStackTrace();
PlotSquared.debug("&c=========================================");
if (Settings.DEBUG) {
logger.error("[P2] Could not read: {}", file);
logger.error("[P2] Renamed to: {}", file);
logger.error("[P2] ============ Full stacktrace ============");
ex.printStackTrace();
logger.error("[P2] =========================================");
}
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -32,7 +32,7 @@ import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.comment.PlotComment;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.util.task.RunnableVal;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.List;
@ -345,7 +345,7 @@ public interface AbstractDB {
*
* @param plot The Plot to get comments from
*/
void getComments(@NotNull Plot plot, String inbox, RunnableVal<List<PlotComment>> whenDone);
void getComments(@Nonnull Plot plot, String inbox, RunnableVal<List<PlotComment>> whenDone);
void createPlotAndSettings(Plot plot, Runnable whenDone);

View File

@ -27,10 +27,13 @@ package com.plotsquared.core.database;
import com.google.common.base.Charsets;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.Storage;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.listener.PlotListener;
import com.plotsquared.core.location.BlockLoc;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
@ -43,11 +46,14 @@ import com.plotsquared.core.plot.flag.FlagParseException;
import com.plotsquared.core.plot.flag.GlobalFlagContainer;
import com.plotsquared.core.plot.flag.PlotFlag;
import com.plotsquared.core.plot.flag.types.BlockTypeListFlag;
import com.plotsquared.core.util.EventDispatcher;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.StringMan;
import com.plotsquared.core.util.task.RunnableVal;
import com.plotsquared.core.util.task.TaskManager;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
@ -79,6 +85,8 @@ import java.util.concurrent.atomic.AtomicInteger;
@SuppressWarnings("SqlDialectInspection")
public class SQLManager implements AbstractDB {
private static final Logger logger = LoggerFactory.getLogger("P2/" + SQLManager.class.getSimpleName());
// Public final
public final String SET_OWNER;
public final String GET_ALL_PLOTS;
@ -128,6 +136,10 @@ public class SQLManager implements AbstractDB {
private Connection connection;
private boolean closed = false;
private final EventDispatcher eventDispatcher;
private final PlotListener plotListener;
private final YamlConfiguration worldConfiguration;
/**
* Constructor
*
@ -136,9 +148,16 @@ public class SQLManager implements AbstractDB {
* @throws SQLException
* @throws ClassNotFoundException
*/
public SQLManager(final Database database, String prefix, boolean debug)
public SQLManager(@Nonnull final Database database,
@Nonnull final String prefix,
@Nonnull final EventDispatcher eventDispatcher,
@Nonnull final PlotListener plotListener,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration)
throws SQLException, ClassNotFoundException {
// Private final
this.eventDispatcher = eventDispatcher;
this.plotListener = plotListener;
this.worldConfiguration = worldConfiguration;
this.database = database;
this.connection = database.openConnection();
this.mySQL = database instanceof MySQL;
@ -250,7 +269,7 @@ public class SQLManager implements AbstractDB {
return this.notifyTasks;
}
public synchronized void addPlotTask(@NotNull Plot plot, UniqueStatement task) {
public synchronized void addPlotTask(@Nonnull Plot plot, UniqueStatement task) {
Queue<UniqueStatement> tasks = this.plotTasks.get(plot);
if (tasks == null) {
tasks = new ConcurrentLinkedQueue<>();
@ -355,11 +374,12 @@ public class SQLManager implements AbstractDB {
try {
task.run();
} catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] There was an error updating the database.");
logger.error("[P2] - It will be corrected on shutdown");
e.printStackTrace();
PlotSquared.debug("========================================");
logger.error("[P2] ========================================");
}
}
commit();
@ -409,12 +429,12 @@ public class SQLManager implements AbstractDB {
}
lastTask = task;
} catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] There was an error updating the database.");
logger.error("[P2] - It will be corrected on shutdown");
logger.error("[P2] ========================================");
e.printStackTrace();
PlotSquared.debug("========================================");
logger.error("[P2] ========================================");
}
}
if (statement != null && task != null) {
@ -454,12 +474,12 @@ public class SQLManager implements AbstractDB {
}
lastTask = task;
} catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] There was an error updating the database.");
logger.error("[P2] - It will be corrected on shutdown");
logger.error("[P2] ========================================");
e.printStackTrace();
PlotSquared.debug("========================================");
logger.error("[P2] ========================================");
}
}
if (statement != null && task != null) {
@ -500,12 +520,12 @@ public class SQLManager implements AbstractDB {
}
lastTask = task;
} catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] There was an error updating the database.");
logger.error("[P2] - It will be corrected on shutdown");
logger.error("[P2] ========================================");
e.printStackTrace();
PlotSquared.debug("========================================");
logger.error("[P2] ========================================");
}
}
if (statement != null && task != null) {
@ -529,12 +549,12 @@ public class SQLManager implements AbstractDB {
this.plotTasks.clear();
}
} catch (Throwable e) {
PlotSquared.debug("============ DATABASE ERROR ============");
PlotSquared.debug("There was an error updating the database.");
PlotSquared.debug(" - It will be corrected on shutdown");
PlotSquared.debug("========================================");
logger.error("[P2] ============ DATABASE ERROR ============");
logger.error("[P2] There was an error updating the database.");
logger.error("[P2] - It will be corrected on shutdown");
logger.error("[P2] ========================================");
e.printStackTrace();
PlotSquared.debug("========================================");
logger.error("[P2] ========================================");
}
return false;
}
@ -622,9 +642,7 @@ public class SQLManager implements AbstractDB {
}
})))));
} catch (SQLException e) {
e.printStackTrace();
PlotSquared
.debug("&7[WARN] Failed to set all flags and member tiers for plots");
logger.warn("[P2] Failed to set all flags and member tiers for plots", e);
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
@ -633,8 +651,7 @@ public class SQLManager implements AbstractDB {
}
});
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug("&7[WARN] Failed to set all helpers for plots");
logger.warn("[P2] Warning! Failed to set all helper for plots", e);
try {
SQLManager.this.connection.commit();
} catch (SQLException e1) {
@ -703,21 +720,19 @@ public class SQLManager implements AbstractDB {
try {
preparedStatement.executeBatch();
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "Failed to store flag values for plot with entry ID: " + plot.getId());
logger.error("[P2] Failed to store flag values for plot with entry ID: {}", plot);
e.printStackTrace();
continue;
}
PlotSquared.debug(Captions.PREFIX.getTranslated()
+ "- Finished converting flags for plot with entry ID: " + plot.getId());
if (Settings.DEBUG) {
logger.info("[P2] - Finished converting flag values for plot with entry ID: {}",
plot.getId());
}
}
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store flag values:");
e.printStackTrace();
logger.error("[P2] Failed to store flag values", e);
}
PlotSquared.log(
Captions.PREFIX.getTranslated() + "Finished converting flags (" + plots.size()
+ " plots processed)");
logger.info("[P2] Finished converting flags ({} plots processed)", plots.size());
whenDone.run();
}
@ -825,8 +840,6 @@ public class SQLManager implements AbstractDB {
last = subList.size();
preparedStmt.addBatch();
}
PlotSquared.debug(
"&aBatch 1: " + count + " | " + objList.get(0).getClass().getCanonicalName());
preparedStmt.executeBatch();
preparedStmt.clearParameters();
preparedStmt.close();
@ -836,8 +849,8 @@ public class SQLManager implements AbstractDB {
return;
} catch (SQLException e) {
if (this.mySQL) {
logger.error("[P2] 1: | {}", objList.get(0).getClass().getCanonicalName());
e.printStackTrace();
PlotSquared.debug("&cERROR 1: | " + objList.get(0).getClass().getCanonicalName());
}
}
try {
@ -869,26 +882,23 @@ public class SQLManager implements AbstractDB {
last = subList.size();
preparedStmt.addBatch();
}
PlotSquared.debug(
"&aBatch 2: " + count + " | " + objList.get(0).getClass().getCanonicalName());
preparedStmt.executeBatch();
preparedStmt.clearParameters();
preparedStmt.close();
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&cERROR 2: | " + objList.get(0).getClass().getCanonicalName());
PlotSquared.debug("&6[WARN] Could not bulk save!");
logger.error("[P2] 2: | {}", objList.get(0).getClass().getCanonicalName());
logger.error("[P2] Could not bulk save!");
try (PreparedStatement preparedStmt = this.connection
.prepareStatement(mod.getCreateSQL())) {
for (T obj : objList) {
mod.setSQL(preparedStmt, obj);
preparedStmt.addBatch();
}
PlotSquared.debug("&aBatch 3");
preparedStmt.executeBatch();
} catch (SQLException e3) {
logger.error("[P2] Failed to save all", e);
e3.printStackTrace();
PlotSquared.debug("&c[ERROR] Failed to save all!");
}
}
if (whenDone != null) {
@ -939,9 +949,7 @@ public class SQLManager implements AbstractDB {
try {
preparedStatement.executeBatch();
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "Failed to store settings values for plot with entry ID: "
+ legacySettings.id);
logger.error("[P2] Failed to store settings for plot with entry ID: {}", legacySettings.id);
e.printStackTrace();
continue;
}
@ -953,18 +961,13 @@ public class SQLManager implements AbstractDB {
try {
preparedStatement.executeBatch();
} catch (final Exception e) {
PlotSquared
.log(Captions.PREFIX.getTranslated() + "Failed to store settings values");
e.printStackTrace();
logger.error("[P2] Failed to store settings", e);
}
}
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store settings values:");
e.printStackTrace();
logger.error("[P2] Failed to store settings", e);
}
PlotSquared.log(
Captions.PREFIX.getTranslated() + "Finished converting settings (" + myList.size()
+ " plots processed)");
logger.info("[P2] Finished converting settihgs ({} plots processed)", myList.size());
whenDone.run();
}
@ -1143,7 +1146,6 @@ public class SQLManager implements AbstractDB {
return;
}
boolean addConstraint = create == tables.length;
PlotSquared.debug("Creating tables");
try (Statement stmt = this.connection.createStatement()) {
if (this.mySQL) {
stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + this.prefix + "plot` ("
@ -1383,9 +1385,6 @@ public class SQLManager implements AbstractDB {
* @param plot
*/
@Override public void delete(final Plot plot) {
PlotSquared.debug(
"Deleting plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: "
+ plot.getOwnerAbs() + " Index: " + plot.temp);
deleteSettings(plot);
deleteDenied(plot);
deleteHelpers(plot);
@ -1411,9 +1410,6 @@ public class SQLManager implements AbstractDB {
* @param plot
*/
@Override public void createPlotSettings(final int id, Plot plot) {
PlotSquared.debug(
"Creating plot... Id: " + plot.getId() + " World: " + plot.getWorldName() + " Owner: "
+ plot.getOwnerAbs() + " Index: " + id);
addPlotTask(plot, new UniqueStatement("createPlotSettings") {
@Override public void set(PreparedStatement statement) throws SQLException {
statement.setInt(1, id);
@ -1571,7 +1567,6 @@ public class SQLManager implements AbstractDB {
"SELECT plot_plot_id, user_uuid, COUNT(*) FROM " + this.prefix + table
+ " GROUP BY plot_plot_id, user_uuid HAVING COUNT(*) > 1");
if (result.next()) {
PlotSquared.debug("BACKING UP: " + this.prefix + table);
result.close();
statement.executeUpdate(
"CREATE TABLE " + this.prefix + table + "_tmp AS SELECT * FROM "
@ -1581,7 +1576,6 @@ public class SQLManager implements AbstractDB {
"CREATE TABLE " + this.prefix + table + " AS SELECT * FROM "
+ this.prefix + table + "_tmp");
statement.executeUpdate("DROP TABLE " + this.prefix + table + "_tmp");
PlotSquared.debug("RESTORING: " + this.prefix + table);
}
}
} catch (SQLException e2) {
@ -1645,40 +1639,20 @@ public class SQLManager implements AbstractDB {
try {
String flag_str =
split[1].replaceAll("¯", ":").replaceAll("\u00B4", ",");
/*PlotFlag<?, ?> flag = GlobalFlagContainer.getInstance().getFlagFromString(split[0]);
if (flag == null) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Flag not found and therefore ignored: " + split[0]);
continue;
}*/
flagMap.get(id).put(split[0], flag_str);
} catch (Exception e) {
e.printStackTrace();
}
} /*else {
element = element.replaceAll("\u00AF", ":").replaceAll("\u00B4", ",");
if (StringMan
.isAlpha(element.replaceAll("_", "").replaceAll("-", ""))) {
PlotFlag<?, ?> flag = GlobalFlagContainer.getInstance().getFlagFromString(element);
if (flag == null) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Flag not found and therefore ignored: " + element);
}
} else {
PlotSquared.log(Captions.PREFIX.getTranslated() + "INVALID FLAG: " + element);
}
}*/
}
}
}
}
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to load old flag values:");
e.printStackTrace();
logger.error("[P2] Failed to load old flag values", e);
return false;
}
PlotSquared.log(Captions.PREFIX.getTranslated() + "Loaded " + flagMap.size()
+ " plot flag collections...");
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "Attempting to store these flags in the new table...");
//
logger.info("[P2] Loaded {} plot flag collections...", flagMap.size());
logger.info("[P2] Attempting to store these flags in the new table...");
try (final PreparedStatement preparedStatement = this.connection.prepareStatement(
"INSERT INTO `" + SQLManager.this.prefix
+ "plot_flags`(`plot_id`, `flag`, `value`) VALUES(?, ?, ?)")) {
@ -1706,9 +1680,7 @@ public class SQLManager implements AbstractDB {
try {
preparedStatement.executeBatch();
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated()
+ "Failed to store flag values for plot with entry ID: " + plotFlagEntry
.getKey());
logger.error("[P2] Failed to store flag values for plot with entry ID: {}", plotFlagEntry.getKey());
e.printStackTrace();
continue;
}
@ -1716,19 +1688,17 @@ public class SQLManager implements AbstractDB {
if (System.currentTimeMillis() - timeStarted >= 1000L || plotsProcessed >= flagMap
.size()) {
timeStarted = System.currentTimeMillis();
PlotSquared.log(
Captions.PREFIX.getTranslated() + "... Flag conversion in progress. "
+ String.format("%.1f", ((float) flagsProcessed / totalFlags) * 100)
+ "% Done");
logger.info("[P2] ... Flag conversion in progress. {}% done",
String.format("%.1f", ((float) flagsProcessed / totalFlags) * 100));
}
PlotSquared.debug(Captions.PREFIX.getTranslated()
+ "- Finished converting flags for plot with entry ID: " + plotFlagEntry
.getKey());
if (Settings.DEBUG) {
logger.info("[P2] - Finished converting flags for plot with entry ID: {}",
plotFlagEntry.getKey());
}
}
} catch (final Exception e) {
PlotSquared.log(Captions.PREFIX.getTranslated() + "Failed to store flag values:");
e.printStackTrace();
logger.error("[P2] Failed to store flag values", e);
return false;
}
return true;
@ -1742,9 +1712,8 @@ public class SQLManager implements AbstractDB {
HashMap<Integer, Plot> plots = new HashMap<>();
try {
HashSet<String> areas = new HashSet<>();
if (PlotSquared.get().worlds.contains("worlds")) {
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection("worlds");
if (this.worldConfiguration.contains("worlds")) {
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection("worlds");
if (worldSection != null) {
for (String worldKey : worldSection.getKeys(false)) {
areas.add(worldKey);
@ -1820,9 +1789,8 @@ public class SQLManager implements AbstractDB {
time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(parsable)
.getTime();
} catch (ParseException e) {
PlotSquared.debug(
"Could not parse date for plot: #" + id + "(" + areaID + ";"
+ plot_id + ") (" + parsable + ")");
logger.error("[P2] Could not parse date for plot: #{}({};{}) ({})",
id, areaID, plot_id, parsable);
time = System.currentTimeMillis() + id;
}
}
@ -1835,10 +1803,9 @@ public class SQLManager implements AbstractDB {
if (last != null) {
if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(last.temp);
} else {
PlotSquared.debug(
"&cPLOT #" + id + "(" + last + ") in `" + this.prefix
+ "plot` is a duplicate. Delete this plot or set `database-purger: true` in the settings.yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Plot #{}({}) in `{}plot` is a duplicate."
+ " Delete this plot or set `database-purger: true` in the settings.yml", id, last, this.prefix);
}
}
} else {
@ -1868,10 +1835,9 @@ public class SQLManager implements AbstractDB {
plot.getSettings().getRatings().put(user, r.getInt("rating"));
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot
+ ") in `plot_rating` does not exist. Create this plot or set `database-purger: true` in the "
+ "settings.yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_rating` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
deleteRows(toDelete, this.prefix + "plot_rating", "plot_plot_id");
@ -1897,10 +1863,9 @@ public class SQLManager implements AbstractDB {
plot.getTrusted().add(user);
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot
+ ") in `plot_helpers` does not exist. Create this plot or set `database-purger: true` in the settings"
+ ".yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_helpers` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
deleteRows(toDelete, this.prefix + "plot_helpers", "plot_plot_id");
@ -1925,10 +1890,9 @@ public class SQLManager implements AbstractDB {
plot.getMembers().add(user);
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot
+ ") in `plot_trusted` does not exist. Create this plot or set `database-purger: true` in the settings"
+ ".yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_trusted` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
deleteRows(toDelete, this.prefix + "plot_trusted", "plot_plot_id");
@ -1953,9 +1917,9 @@ public class SQLManager implements AbstractDB {
plot.getDenied().add(user);
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cENTRY " + id
+ " in `plot_denied` does not exist. Create this plot or set `database-purger: true` in the settings.yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_denied` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
deleteRows(toDelete, this.prefix + "plot_denied", "plot_plot_id");
@ -1976,19 +1940,15 @@ public class SQLManager implements AbstractDB {
final PlotFlag<?, ?> plotFlag =
GlobalFlagContainer.getInstance().getFlagFromString(flag);
if (plotFlag == null) {
PlotSquared.debug("Adding unknown flag to plot with ID " + id);
plot.getFlagContainer().addUnknownFlag(flag, value);
} else {
try {
plot.getFlagContainer().addFlag(plotFlag.parse(value));
} catch (final FlagParseException e) {
e.printStackTrace();
PlotSquared
.debug("Plot with ID " + id + " has an invalid value:");
PlotSquared.debug(Captions.FLAG_PARSE_ERROR.getTranslated()
.replace("%flag_name%", plotFlag.getName())
.replace("%flag_value%", e.getValue())
.replace("%error%", e.getErrorMessage()));
logger.error("[P2] Plot with ID {} has an invalid value:", id);
logger.error("[P2] Failed to parse flag '{}', value '{}': {}",
plotFlag.getName(), e.getValue(), e.getErrorMessage());
if (!invalidFlags.containsKey(plot)) {
invalidFlags.put(plot, new ArrayList<>());
}
@ -1997,9 +1957,9 @@ public class SQLManager implements AbstractDB {
}
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cPlot " + id
+ " in `plot_flags` does not exist. Create this plot or set `database-purger: true` in the settings.yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_flags` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
BlockTypeListFlag.skipCategoryVerification =
@ -2008,9 +1968,11 @@ public class SQLManager implements AbstractDB {
for (final Map.Entry<Plot, Collection<PlotFlag<?, ?>>> plotFlagEntry : invalidFlags
.entrySet()) {
for (final PlotFlag<?, ?> flag : plotFlagEntry.getValue()) {
PlotSquared.debug("&cPlot \"" + plotFlagEntry.getKey() + "\""
+ " had an invalid flag (" + flag.getName()
+ "). A fix has been attempted.");
if (Settings.DEBUG) {
logger.info(
"Plot {} has an invalid flag ({}). A fix has been attempted",
plotFlagEntry.getKey(), flag.getName());
}
removeFlag(plotFlagEntry.getKey(), flag);
}
}
@ -2051,10 +2013,9 @@ public class SQLManager implements AbstractDB {
plot.getSettings().setMerged(merged);
} else if (Settings.Enabled_Components.DATABASE_PURGER) {
toDelete.add(id);
} else {
PlotSquared.debug("&cENTRY #" + id + "(" + plot
+ ") in `plot_settings` does not exist. Create this plot or set `database-purger: true` in the settings"
+ ".yml.");
} else if (Settings.DEBUG) {
logger.info("[P2] Entry #{}({}) in `plot_settings` does not exist."
+ " Create this plot or set `database-purger: true` in settings.yml", id, plot);
}
}
deleteRows(toDelete, this.prefix + "plot_settings", "plot_plot_id");
@ -2070,16 +2031,16 @@ public class SQLManager implements AbstractDB {
for (Entry<String, AtomicInteger> entry : noExist.entrySet()) {
String worldName = entry.getKey();
invalidPlot = true;
PlotSquared.debug("&c[WARNING] Found " + entry.getValue().intValue()
+ " plots in DB for non existent world; '" + worldName + "'.");
if (Settings.DEBUG) {
logger.info("[P2] Warning! Found {} plots in DB for non existent world: '{}'",
entry.getValue().intValue(), worldName);
}
}
if (invalidPlot) {
PlotSquared.debug(
"&c[WARNING] - Please create the world/s or remove the plots using the purge command");
if (invalidPlot && Settings.DEBUG) {
logger.info("[P2] Warning! Please create the world(s) or remove the plots using the purge command");
}
} catch (SQLException e) {
PlotSquared.debug("&7[WARN] Failed to load plots.");
e.printStackTrace();
logger.error("[P2] Failed to load plots", e);
}
return newPlots;
}
@ -2120,9 +2081,7 @@ public class SQLManager implements AbstractDB {
preparedStatement.setInt(3, id2);
preparedStatement.execute();
} catch (final Exception e) {
PlotSquared.log(
Captions.PREFIX.getTranslated() + "Failed to persist swap of " + plot1 + " and "
+ plot2 + "!");
logger.error("[P2] Failed to persist wap of {} and {}", plot1, plot2);
e.printStackTrace();
future.complete(false);
return;
@ -2220,8 +2179,6 @@ public class SQLManager implements AbstractDB {
int count = 0;
int last = -1;
for (int j = 0; j <= amount; j++) {
int purging = Math.max(j * packet, size);
PlotSquared.debug("Purging " + purging + " / " + size);
List<Integer> subList =
uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet));
if (subList.isEmpty()) {
@ -2267,12 +2224,13 @@ public class SQLManager implements AbstractDB {
commit();
}
} catch (SQLException e) {
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE PLOTS!");
logger.error("[P2] Failed to purge plots", e);
return;
}
}
PlotSquared.debug("&6[INFO] SUCCESSFULLY PURGED " + uniqueIds.size() + " PLOTS!");
if (Settings.DEBUG) {
logger.info("[P2] Successfully purged {} plots", uniqueIds.size());
}
}
});
}
@ -2295,8 +2253,8 @@ public class SQLManager implements AbstractDB {
}
purgeIds(ids);
} catch (SQLException e) {
logger.error("[P2] Failed to purge area '{}'", area);
e.printStackTrace();
PlotSquared.debug("&c[ERROR] FAILED TO PURGE AREA '" + area + "'!");
}
for (Iterator<PlotId> iterator = plots.iterator(); iterator.hasNext(); ) {
PlotId plotId = iterator.next();
@ -2376,7 +2334,7 @@ public class SQLManager implements AbstractDB {
}
@Override
public void getComments(@NotNull Plot plot, final String inbox,
public void getComments(@Nonnull Plot plot, final String inbox,
final RunnableVal<List<PlotComment>> whenDone) {
addPlotTask(plot, new UniqueStatement("getComments_" + plot) {
@Override public void set(PreparedStatement statement) throws SQLException {
@ -2552,8 +2510,7 @@ public class SQLManager implements AbstractDB {
}
}
} catch (SQLException e) {
PlotSquared
.debug("&7[WARN] Failed to fetch rating for plot " + plot.getId().toString());
logger.error("[P2] Failed to fetch rating for plot {}", plot.getId().toString());
e.printStackTrace();
}
return map;
@ -2706,9 +2663,8 @@ public class SQLManager implements AbstractDB {
HashMap<Integer, PlotCluster> clusters = new HashMap<>();
try {
HashSet<String> areas = new HashSet<>();
if (PlotSquared.get().worlds.contains("worlds")) {
ConfigurationSection worldSection =
PlotSquared.get().worlds.getConfigurationSection("worlds");
if (this.worldConfiguration.contains("worlds")) {
ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection("worlds");
if (worldSection != null) {
for (String worldKey : worldSection.getKeys(false)) {
areas.add(worldKey);
@ -2773,9 +2729,9 @@ public class SQLManager implements AbstractDB {
cluster = clusters.get(id);
if (cluster != null) {
cluster.helpers.add(user);
} else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster
+ ") in cluster_helpers does not exist. Please create the cluster or remove this entry.");
} else if (Settings.DEBUG) {
logger.warn("[P2] Cluster #{}({}) in cluster_helpers does not exist."
+ " Please create the cluster or remove this entry", id, cluster);
}
}
// Getting invited
@ -2792,9 +2748,9 @@ public class SQLManager implements AbstractDB {
cluster = clusters.get(id);
if (cluster != null) {
cluster.invited.add(user);
} else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster
+ ") in cluster_invited does not exist. Please create the cluster or remove this entry.");
} else if (Settings.DEBUG) {
logger.warn("[P2] Cluster #{}({}) in cluster_helpers does not exist."
+ " Please create the cluster or remove this entry", id, cluster);
}
}
resultSet =
@ -2827,9 +2783,9 @@ public class SQLManager implements AbstractDB {
merged[3 - i] = (m & 1 << i) != 0;
}
cluster.settings.setMerged(merged);
} else {
PlotSquared.debug("&cCluster #" + id + "(" + cluster
+ ") in cluster_settings does not exist. Please create the cluster or remove this entry.");
} else if (Settings.DEBUG) {
logger.warn("[P2] Cluster #{}({}) in cluster_helpers does not exist."
+ " Please create the cluster or remove this entry", id, cluster);
}
}
resultSet.close();
@ -2838,16 +2794,13 @@ public class SQLManager implements AbstractDB {
for (Entry<String, Integer> entry : noExist.entrySet()) {
String a = entry.getKey();
invalidPlot = true;
PlotSquared.debug("&c[WARNING] Found " + noExist.get(a)
+ " clusters in DB for non existent area; '" + a + "'.");
logger.warn("[P2] Warning! Found {} clusters in DB for non existent area; '{}'", noExist.get(a), a);
}
if (invalidPlot) {
PlotSquared.debug(
"&c[WARNING] - Please create the world/s or remove the clusters using the purge command");
logger.warn("[P2] Warning! Please create the world(s) or remove the clusters using the purge command");
}
} catch (SQLException e) {
PlotSquared.debug("&7[WARN] Failed to load clusters.");
e.printStackTrace();
logger.error("[P2] Failed to load clusters", e);
}
return newClusters;
}
@ -3039,8 +2992,7 @@ public class SQLManager implements AbstractDB {
if (!isValid()) {
reconnect();
}
PlotSquared.debug(
"$1All DB transactions during this session are being validated (This may take a while if corrections need to be made)");
logger.info("[P2] All DB transactions during this session are being validated (This may take a while if corrections need to be made)");
commit();
while (true) {
if (!sendBatch()) {
@ -3061,31 +3013,27 @@ public class SQLManager implements AbstractDB {
continue;
}
if (plot.getArea() == null) {
PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!");
PlotSquared.debug("PLOT AREA CANNOT BE NULL! SKIPPING PLOT!");
logger.error("[P2] CRITICAL ERROR IN VALIDATION TASK!");
logger.error("[P2] PLOT AREA CANNOT BE NULL! SKIPPING PLOT!");
continue;
}
if (database == null) {
PlotSquared.debug("CRITICAL ERROR IN VALIDATION TASK!");
PlotSquared.debug("DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!!");
logger.error("[P2] CRITICAL ERROR IN VALIDATION TASK!");
logger.error("[P2] DATABASE VARIABLE CANNOT BE NULL! NOW ENDING VALIDATION!");
break;
}
HashMap<PlotId, Plot> worldPlots = database.get(plot.getArea().toString());
if (worldPlots == null) {
PlotSquared.debug("&8 - &7Creating plot (1): " + plot);
toCreate.add(plot);
continue;
}
Plot dataPlot = worldPlots.remove(plot.getId());
if (dataPlot == null) {
PlotSquared.debug("&8 - &7Creating plot (2): " + plot);
toCreate.add(plot);
continue;
}
// owner
if (!plot.getOwnerAbs().equals(dataPlot.getOwnerAbs())) {
PlotSquared.debug("&8 - &7Setting owner: " + plot + " -> " + MainUtil
.getName(plot.getOwnerAbs()));
setOwner(plot, plot.getOwnerAbs());
}
// trusted
@ -3094,9 +3042,6 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getTrusted().clone();
toRemove.removeAll(plot.getTrusted());
toAdd.removeAll(dataPlot.getTrusted());
PlotSquared.debug(
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " trusted for: "
+ plot);
if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) {
removeTrusted(plot, uuid);
@ -3113,9 +3058,6 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getMembers().clone();
toRemove.removeAll(plot.getMembers());
toAdd.removeAll(dataPlot.getMembers());
PlotSquared.debug(
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " members for: "
+ plot);
if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) {
removeMember(plot, uuid);
@ -3132,9 +3074,6 @@ public class SQLManager implements AbstractDB {
HashSet<UUID> toRemove = (HashSet<UUID>) dataPlot.getDenied().clone();
toRemove.removeAll(plot.getDenied());
toAdd.removeAll(dataPlot.getDenied());
PlotSquared.debug(
"&8 - &7Correcting " + (toAdd.size() + toRemove.size()) + " denied for: "
+ plot);
if (!toRemove.isEmpty()) {
for (UUID uuid : toRemove) {
removeDenied(plot, uuid);
@ -3149,7 +3088,6 @@ public class SQLManager implements AbstractDB {
boolean[] pm = plot.getMerged();
boolean[] dm = dataPlot.getMerged();
if (pm[0] != dm[0] || pm[1] != dm[1]) {
PlotSquared.debug(" - Correcting merge for: " + plot);
setMerged(dataPlot, plot.getMerged());
}
Set<PlotFlag<?, ?>> pf = plot.getFlags();
@ -3157,7 +3095,6 @@ public class SQLManager implements AbstractDB {
if (!pf.isEmpty() && !df.isEmpty()) {
if (pf.size() != df.size() || !StringMan
.isEqual(StringMan.joinOrdered(pf, ","), StringMan.joinOrdered(df, ","))) {
PlotSquared.debug(" - Correcting flags for: " + plot);
// setFlags(plot, pf);
// TODO: Re-implement
}
@ -3168,8 +3105,7 @@ public class SQLManager implements AbstractDB {
HashMap<PlotId, Plot> map = entry.getValue();
if (!map.isEmpty()) {
for (Entry<PlotId, Plot> entry2 : map.entrySet()) {
PlotSquared.debug("$1Plot was deleted: " + entry2.getValue().toString()
+ "// TODO implement this when sure safe");
// TODO implement this when sure safe"
}
}
}

View File

@ -26,6 +26,8 @@
package com.plotsquared.core.database;
import com.plotsquared.core.PlotSquared;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
@ -40,6 +42,8 @@ import java.sql.Statement;
*/
public class SQLite extends Database {
private static final Logger logger = LoggerFactory.getLogger("P2/" + SQLite.class.getSimpleName());
private final String dbLocation;
private Connection connection;
@ -56,15 +60,15 @@ public class SQLite extends Database {
if (checkConnection()) {
return this.connection;
}
if (!PlotSquared.get().IMP.getDirectory().exists()) {
PlotSquared.get().IMP.getDirectory().mkdirs();
if (!PlotSquared.platform().getDirectory().exists()) {
PlotSquared.platform().getDirectory().mkdirs();
}
File file = new File(this.dbLocation);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ignored) {
PlotSquared.debug("&cUnable to create database!");
logger.error("[P2] Unable to create database");
}
}
Class.forName("org.sqlite.JDBC");

View File

@ -28,7 +28,7 @@ package com.plotsquared.core.events;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotId;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.List;
@ -50,8 +50,8 @@ public final class PlotAutoMergeEvent extends PlotEvent implements CancellablePl
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotAutoMergeEvent(@NotNull final String world, @NotNull final Plot plot,
@NotNull final List<PlotId> plots) {
public PlotAutoMergeEvent(@Nonnull final String world, @Nonnull final Plot plot,
@Nonnull final List<PlotId> plots) {
super(plot);
this.world = world;
this.plots = plots;

View File

@ -28,7 +28,7 @@ package com.plotsquared.core.events;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotId;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable;
import java.util.UUID;

View File

@ -26,7 +26,7 @@
package com.plotsquared.core.events;
import com.plotsquared.core.plot.Plot;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
public abstract class PlotEvent {
@ -51,7 +51,7 @@ public abstract class PlotEvent {
*
* @return the event class name
*/
@NotNull public String getEventName() {
@Nonnull public String getEventName() {
if (name == null) {
name = getClass().getSimpleName();
}

View File

@ -30,7 +30,7 @@ import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
/**
* Event called when several plots are merged
@ -53,8 +53,8 @@ public final class PlotMergeEvent extends PlotPlayerEvent implements Cancellable
* @param max Max merge size
* @param player The player attempting the merge
*/
public PlotMergeEvent(@NotNull final String world, @NotNull final Plot plot,
@NotNull final Direction dir, final int max, PlotPlayer player) {
public PlotMergeEvent(@Nonnull final String world, @Nonnull final Plot plot,
@Nonnull final Direction dir, final int max, PlotPlayer player) {
super(player, plot);
this.world = world;
this.dir = dir;

View File

@ -28,7 +28,7 @@ package com.plotsquared.core.events;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.Rating;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable;
public class PlotRateEvent extends PlotEvent implements CancellablePlotEvent {

View File

@ -29,7 +29,7 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
/**
* Event called when several merged plots are unlinked
@ -52,7 +52,7 @@ public final class PlotUnlinkEvent extends PlotEvent implements CancellablePlotE
* @param createSign Whether to regenerate signs
* @param reason The {@link REASON} for the unlink
*/
public PlotUnlinkEvent(@NotNull final PlotArea area, Plot plot, boolean createRoad,
public PlotUnlinkEvent(@Nonnull final PlotArea area, Plot plot, boolean createRoad,
boolean createSign, REASON reason) {
super(plot);
this.area = area;

View File

@ -32,7 +32,6 @@ import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.queue.AreaBoundDelegateLocalBlockQueue;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.queue.LocationOffsetDelegateLocalBlockQueue;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
@ -40,8 +39,8 @@ import com.plotsquared.core.util.RegionUtil;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Set;
@ -55,7 +54,7 @@ public class AugmentedUtils {
enabled = true;
}
public static boolean generate(@Nullable Object chunkObject, @NotNull final String world,
public static boolean generate(@Nullable Object chunkObject, @Nonnull final String world,
final int chunkX, final int chunkZ, LocalBlockQueue queue) {
if (!enabled) {
return false;
@ -68,7 +67,7 @@ public class AugmentedUtils {
// entire chunk
CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15);
// Query for plot areas in the chunk
Set<PlotArea> areas = PlotSquared.get().getPlotAreas(world, region);
final Set<PlotArea> areas = PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region);
if (areas.isEmpty()) {
return false;
}
@ -87,7 +86,7 @@ public class AugmentedUtils {
IndependentPlotGenerator generator = area.getGenerator();
// Mask
if (queue == null) {
queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false);
queue.setChunkObject(chunkObject);
}
LocalBlockQueue primaryMask;
@ -153,8 +152,8 @@ public class AugmentedUtils {
secondaryMask.setForceSync(true);
ScopedLocalBlockQueue scoped =
new ScopedLocalBlockQueue(secondaryMask, new Location(world, blockX, 0, blockZ),
new Location(world, blockX + 15, 255, blockZ + 15));
new ScopedLocalBlockQueue(secondaryMask, Location.at(world, blockX, 0, blockZ),
Location.at(world, blockX + 15, 255, blockZ + 15));
generator.generateChunk(scoped, area);
generator.populateChunk(scoped, area);
}

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.generator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.location.Direction;
import com.plotsquared.core.location.Location;
@ -32,7 +33,6 @@ import com.plotsquared.core.plot.BlockBucket;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.BlockUtil;
import com.plotsquared.core.util.MathMan;
@ -40,6 +40,7 @@ import com.plotsquared.core.util.RegionManager;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.world.block.BlockTypes;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Optional;
@ -50,10 +51,13 @@ import java.util.Optional;
public class ClassicPlotManager extends SquarePlotManager {
private final ClassicPlotWorld classicPlotWorld;
private final RegionManager regionManager;
public ClassicPlotManager(ClassicPlotWorld classicPlotWorld) {
super(classicPlotWorld);
public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld,
@Nonnull final RegionManager regionManager) {
super(classicPlotWorld, regionManager);
this.classicPlotWorld = classicPlotWorld;
this.regionManager = regionManager;
}
@Override public boolean setComponent(PlotId plotId, String component, Pattern blocks) {
@ -88,13 +92,13 @@ public class ClassicPlotManager extends SquarePlotManager {
.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) {
setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern());
}
return GlobalBlockQueue.IMP.addEmptyTask(whenDone);
return PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(whenDone);
}
public boolean setFloor(PlotId plotId, Pattern blocks) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot.isBasePlot()) {
return RegionManager.manager.setCuboids(classicPlotWorld, plot.getRegions(), blocks,
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks,
classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT);
}
return false;
@ -103,8 +107,7 @@ public class ClassicPlotManager extends SquarePlotManager {
public boolean setAll(PlotId plotId, Pattern blocks) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot.isBasePlot()) {
return RegionManager.manager
.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight());
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight());
}
return false;
}
@ -112,7 +115,7 @@ public class ClassicPlotManager extends SquarePlotManager {
public boolean setAir(PlotId plotId, Pattern blocks) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot.isBasePlot()) {
return RegionManager.manager.setCuboids(classicPlotWorld, plot.getRegions(), blocks,
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks,
classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight());
}
return false;
@ -121,7 +124,7 @@ public class ClassicPlotManager extends SquarePlotManager {
public boolean setMain(PlotId plotId, Pattern blocks) {
Plot plot = classicPlotWorld.getPlotAbs(plotId);
if (plot.isBasePlot()) {
return RegionManager.manager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1,
return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1,
classicPlotWorld.PLOT_HEIGHT - 1);
}
return false;
@ -192,10 +195,10 @@ public class ClassicPlotManager extends SquarePlotManager {
if (plot.isBasePlot()) {
for (CuboidRegion region : plot.getRegions()) {
Location pos1 =
new Location(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(),
Location.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(),
maxY, region.getMinimumPoint().getZ());
Location pos2 =
new Location(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(),
Location.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(),
maxY, region.getMaximumPoint().getZ());
queue.setCuboid(pos1, pos2, blocks);
}
@ -314,31 +317,31 @@ public class ClassicPlotManager extends SquarePlotManager {
int ez = pos2.getZ() + 2;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
int maxY = getWorldHeight();
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx,
Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, maxY, ez - 1),
Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 0, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, 0, ez - 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1),
BlockUtil.get((short) 7, (byte) 0));
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1),
classicPlotWorld.WALL_FILLING.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1,
sz + 1),
new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1,
ez - 1), classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), ex, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1),
classicPlotWorld.WALL_FILLING.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1,
sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1,
ez - 1), classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
return queue.enqueue();
}
@ -351,32 +354,32 @@ public class ClassicPlotManager extends SquarePlotManager {
int sx = pos1.getX() - 2;
int ex = pos2.getX() + 2;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1,
Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
new Location(classicPlotWorld.getWorldName(), ex - 1,
Location.at(classicPlotWorld.getWorldName(), ex - 1,
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 0, sz),
new Location(classicPlotWorld.getWorldName(), ex - 1, 0, ez),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez),
BlockUtil.get((short) 7, (byte) 0));
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz),
classicPlotWorld.WALL_FILLING.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1,
sz),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1,
sz), classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, ez),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, ez),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez),
classicPlotWorld.WALL_FILLING.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1,
ez),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1,
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1,
ez), classicPlotWorld.WALL_BLOCK.toPattern());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
return queue.enqueue();
}
@ -389,15 +392,15 @@ public class ClassicPlotManager extends SquarePlotManager {
int ez = sz + classicPlotWorld.ROAD_WIDTH - 1;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1,
sz + 1), new Location(classicPlotWorld.getWorldName(), ex - 1,
Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1,
sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1,
classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1),
BlockUtil.get((short) 7, (byte) 0));
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT,
ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern());
return queue.enqueue();
}
@ -410,17 +413,17 @@ public class ClassicPlotManager extends SquarePlotManager {
int sz = pos1.getZ() - 1;
int ez = pos2.getZ() + 1;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx,
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
new Location(classicPlotWorld.getWorldName(), ex,
Location.at(classicPlotWorld.getWorldName(), ex,
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1,
ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1),
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1),
classicPlotWorld.TOP_BLOCK.toPattern());
return queue.enqueue();
}
@ -433,17 +436,17 @@ public class ClassicPlotManager extends SquarePlotManager {
int sx = pos1.getX() - 1;
int ex = pos2.getX() + 1;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx,
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
new Location(classicPlotWorld.getWorldName(), ex,
Location.at(classicPlotWorld.getWorldName(), ex,
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1,
ez), classicPlotWorld.MAIN_BLOCK.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz),
new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez),
Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz),
Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez),
classicPlotWorld.TOP_BLOCK.toPattern());
return queue.enqueue();
}
@ -455,17 +458,17 @@ public class ClassicPlotManager extends SquarePlotManager {
int sz = location.getZ() + 1;
int ez = sz + classicPlotWorld.ROAD_WIDTH - 1;
LocalBlockQueue queue = classicPlotWorld.getQueue(false);
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx,
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx,
Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz),
new Location(classicPlotWorld.getWorldName(), ex,
Location.at(classicPlotWorld.getWorldName(), ex,
classicPlotWorld.getPlotManager().getWorldHeight(), ez),
BlockTypes.AIR.getDefaultState());
queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 1, sz),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez),
queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez),
classicPlotWorld.MAIN_BLOCK.toPattern());
queue.setCuboid(
new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz),
new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez),
Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz),
Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez),
classicPlotWorld.TOP_BLOCK.toPattern());
return queue.enqueue();
}
@ -529,8 +532,8 @@ public class ClassicPlotManager extends SquarePlotManager {
*/
@Override public Location getSignLoc(Plot plot) {
plot = plot.getBasePlot(false);
Location bot = plot.getBottomAbs();
return new Location(classicPlotWorld.getWorldName(), bot.getX() - 1,
final Location bot = plot.getBottomAbs();
return Location.at(classicPlotWorld.getWorldName(), bot.getX() - 1,
classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2);
}

View File

@ -25,7 +25,7 @@
*/
package com.plotsquared.core.generator;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.Optional;
@ -51,7 +51,7 @@ public enum ClassicPlotManagerComponent {
return stringValues;
}
public static Optional<ClassicPlotManagerComponent> fromString(@NotNull final String string) {
public static Optional<ClassicPlotManagerComponent> fromString(@Nonnull final String string) {
for (final ClassicPlotManagerComponent classicPlotManagerComponent : values()) {
if (classicPlotManagerComponent.name().equalsIgnoreCase(string)) {
return Optional.of(classicPlotManagerComponent);

View File

@ -28,10 +28,15 @@ package com.plotsquared.core.generator;
import com.plotsquared.core.configuration.ConfigurationNode;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.ConfigurationUtil;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.plot.BlockBucket;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@SuppressWarnings("WeakerAccess")
public abstract class ClassicPlotWorld extends SquarePlotWorld {
@ -53,9 +58,15 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld {
// BlockUtil.get((short) 155, (byte) 0);
public boolean PLOT_BEDROCK = true;
public ClassicPlotWorld(String worldName, String id,
@NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) {
super(worldName, id, generator, min, max);
public ClassicPlotWorld(@Nonnull final String worldName,
@Nullable final String id,
@Nonnull final IndependentPlotGenerator generator,
@Nonnull final PlotId min,
@Nonnull final PlotId max,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@Nonnull final GlobalBlockQueue blockQueue,
@Nullable final EconHandler econHandler) {
super(worldName, id, generator, min, max, worldConfiguration, blockQueue, econHandler);
}
/**
@ -65,7 +76,7 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld {
* command - this may be useful if a config value can be changed at a later date, and has no impact on the actual
* world generation</p>
*/
@NotNull @Override public ConfigurationNode[] getSettingNodes() {
@Nonnull @Override public ConfigurationNode[] getSettingNodes() {
return new ConfigurationNode[] {
new ConfigurationNode("plot.height", this.PLOT_HEIGHT, "Plot height",
ConfigurationUtil.INTEGER),

View File

@ -25,16 +25,23 @@
*/
package com.plotsquared.core.generator;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import org.jetbrains.annotations.NotNull;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public abstract class GridPlotWorld extends PlotArea {
public short SIZE;
public GridPlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator,
PlotId min, PlotId max) {
super(worldName, id, generator, min, max);
public GridPlotWorld(String worldName, String id, @Nonnull IndependentPlotGenerator generator,
PlotId min, PlotId max, @WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@Nonnull final GlobalBlockQueue blockQueue,
@Nullable final EconHandler econHandler) {
super(worldName, id, generator, min, max, worldConfiguration, blockQueue, econHandler);
}
}

View File

@ -26,8 +26,10 @@
package com.plotsquared.core.generator;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.inject.factory.HybridPlotWorldFactory;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
@ -36,12 +38,18 @@ import com.plotsquared.core.util.MathMan;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
public class HybridGen extends IndependentPlotGenerator {
private final HybridPlotWorldFactory hybridPlotWorldFactory;
@Inject public HybridGen(@Nonnull final HybridPlotWorldFactory hybridPlotWorldFactory) {
this.hybridPlotWorldFactory = hybridPlotWorldFactory;
}
@Override public String getName() {
return PlotSquared.imp().getPluginName();
return PlotSquared.platform().getPluginName();
}
private void placeSchem(HybridPlotWorld world, ScopedLocalBlockQueue result, short relativeX,
@ -68,7 +76,7 @@ public class HybridGen extends IndependentPlotGenerator {
}
@Override
public void generateChunk(@NotNull ScopedLocalBlockQueue result, @NotNull PlotArea settings) {
public void generateChunk(@Nonnull ScopedLocalBlockQueue result, @Nonnull PlotArea settings) {
Preconditions.checkNotNull(result, "result cannot be null");
Preconditions.checkNotNull(settings, "settings cannot be null");
@ -221,7 +229,7 @@ public class HybridGen extends IndependentPlotGenerator {
}
@Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return new HybridPlotWorld(world, id, this, min, max);
return this.hybridPlotWorldFactory.create(world, id, this, min, max);
}
@Override public void initialize(PlotArea area) {

View File

@ -34,7 +34,6 @@ import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotAreaTerrainType;
import com.plotsquared.core.plot.PlotAreaType;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
import com.plotsquared.core.util.ChunkManager;
import com.plotsquared.core.util.FileBytes;
@ -48,6 +47,7 @@ import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import lombok.Getter;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
@ -59,10 +59,13 @@ public class HybridPlotManager extends ClassicPlotManager {
public static boolean REGENERATIVE_CLEAR = true;
@Getter private final HybridPlotWorld hybridPlotWorld;
private final RegionManager regionManager;
public HybridPlotManager(HybridPlotWorld hybridPlotWorld) {
super(hybridPlotWorld);
public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld,
@Nonnull final RegionManager regionManager) {
super(hybridPlotWorld, regionManager);
this.hybridPlotWorld = hybridPlotWorld;
this.regionManager = regionManager;
}
@Override public void exportTemplate() throws IOException {
@ -74,7 +77,7 @@ public class HybridPlotManager extends ClassicPlotManager {
.getWorldName() + File.separator;
try {
File sideRoad =
MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), dir + "sideroad.schem");
MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem");
String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator
+ "__TEMP_DIR__" + File.separator;
if (sideRoad.exists()) {
@ -82,12 +85,12 @@ public class HybridPlotManager extends ClassicPlotManager {
Files.readAllBytes(sideRoad.toPath())));
}
File intersection =
MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), dir + "intersection.schem");
MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem");
if (intersection.exists()) {
files.add(new FileBytes(newDir + "intersection.schem",
Files.readAllBytes(intersection.toPath())));
}
File plot = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), dir + "plot.schem");
File plot = MainUtil.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem");
if (plot.exists()) {
files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath())));
}
@ -103,9 +106,8 @@ public class HybridPlotManager extends ClassicPlotManager {
PlotId id2 = new PlotId(id.x + 1, id.y);
Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id);
Location pos1 =
new Location(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1);
Location pos2 = new Location(hybridPlotWorld.getWorldName(), bot.getX(),
Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1);
Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(),
Math.min(getWorldHeight(), 255), top.getZ() + 1);
MainUtil.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
@ -165,9 +167,8 @@ public class HybridPlotManager extends ClassicPlotManager {
PlotId id2 = new PlotId(id.x, id.y + 1);
Location bot = getPlotBottomLocAbs(id2);
Location top = getPlotTopLocAbs(id);
Location pos1 =
new Location(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1);
Location pos2 = new Location(hybridPlotWorld.getWorldName(), top.getX() + 1,
Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1);
Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1,
Math.min(getWorldHeight(), 255), bot.getZ());
MainUtil.resetBiome(hybridPlotWorld, pos1, pos2);
if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
@ -183,10 +184,8 @@ public class HybridPlotManager extends ClassicPlotManager {
super.createRoadSouthEast(plot);
PlotId id = plot.getId();
PlotId id2 = new PlotId(id.x + 1, id.y + 1);
Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1);
Location pos2 = getPlotBottomLocAbs(id2);
pos1.setY(0);
pos2.setY(Math.min(getWorldHeight(), 255));
Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0);
Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255));
LocalBlockQueue queue = hybridPlotWorld.getQueue(false);
createSchemAbs(queue, pos1, pos2, true);
if (hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) {
@ -203,9 +202,9 @@ public class HybridPlotManager extends ClassicPlotManager {
* </p>
*/
@Override public boolean clearPlot(Plot plot, final Runnable whenDone) {
if (RegionManager.manager.notifyClear(this)) {
if (this.regionManager.notifyClear(this)) {
//If this returns false, the clear didn't work
if (RegionManager.manager.handleClear(plot, whenDone, this)) {
if (this.regionManager.handleClear(plot, whenDone, this)) {
return true;
}
}
@ -241,18 +240,18 @@ public class HybridPlotManager extends ClassicPlotManager {
// Set the biome
MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome);
// These two locations are for each component (e.g. bedrock, main block, floor, air)
Location bot = new Location(world, value[2], 0, value[3]);
Location top = new Location(world, value[4], 1, value[5]);
Location bot = Location.at(world, value[2], 0, value[3]);
Location top = Location.at(world, value[4], 1, value[5]);
queue.setCuboid(bot, top, bedrock);
// Each component has a different layer
bot.setY(1);
top.setY(hybridPlotWorld.PLOT_HEIGHT);
bot = bot.withY(1);
top = top.withY(hybridPlotWorld.PLOT_HEIGHT);
queue.setCuboid(bot, top, filling);
bot.setY(hybridPlotWorld.PLOT_HEIGHT);
top.setY(hybridPlotWorld.PLOT_HEIGHT + 1);
bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT);
top = top.withY(hybridPlotWorld.PLOT_HEIGHT + 1);
queue.setCuboid(bot, top, plotfloor);
bot.setY(hybridPlotWorld.PLOT_HEIGHT + 1);
top.setY(getWorldHeight());
bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT + 1);
top = top.withY(getWorldHeight());
queue.setCuboid(bot, top, air);
// And finally set the schematic, the y value is unimportant for this function
pastePlotSchematic(queue, bot, top);
@ -260,7 +259,7 @@ public class HybridPlotManager extends ClassicPlotManager {
}, () -> {
queue.enqueue();
// And notify whatever called this when plot clearing is done
GlobalBlockQueue.IMP.addEmptyTask(whenDone);
PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(whenDone);
}, 10);
return true;
}

View File

@ -25,18 +25,23 @@
*/
package com.plotsquared.core.generator;
import com.google.inject.assistedinject.Assisted;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Captions;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotArea;
import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.PlotManager;
import com.plotsquared.core.plot.schematic.Schematic;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.MathMan;
import com.plotsquared.core.util.RegionManager;
import com.plotsquared.core.util.SchematicHandler;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.CompoundTagBuilder;
@ -51,8 +56,12 @@ import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
@ -60,7 +69,8 @@ import java.util.Locale;
public class HybridPlotWorld extends ClassicPlotWorld {
private static AffineTransform transform = new AffineTransform().rotateY(90);
private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridPlotWorld.class.getSimpleName());
private static final AffineTransform transform = new AffineTransform().rotateY(90);
public boolean ROAD_SCHEMATIC_ENABLED;
public boolean PLOT_SCHEMATIC = false;
public int PLOT_SCHEMATIC_HEIGHT = -1;
@ -72,9 +82,22 @@ public class HybridPlotWorld extends ClassicPlotWorld {
private Location SIGN_LOCATION;
@Getter private File root = null;
public HybridPlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator,
PlotId min, PlotId max) {
super(worldName, id, generator, min, max);
private final RegionManager regionManager;
private final SchematicHandler schematicHandler;
@Inject public HybridPlotWorld(@Assisted("world") final String worldName,
@Nullable @Assisted("id") final String id,
@Assisted @Nonnull final IndependentPlotGenerator generator,
@Nullable @Assisted("min") final PlotId min,
@Nullable @Assisted("max") final PlotId max,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@Nonnull final RegionManager regionManager,
@Nonnull final SchematicHandler schematicHandler,
@Nonnull final GlobalBlockQueue blockQueue,
@Nullable final EconHandler econHandler) {
super(worldName, id, generator, min, max, worldConfiguration, blockQueue, econHandler);
this.regionManager = regionManager;
this.schematicHandler = schematicHandler;
}
public static byte wrap(byte data, int start) {
@ -124,19 +147,17 @@ public class HybridPlotWorld extends ClassicPlotWorld {
return BlockTransformExtent.transform(id, transform);
}
@NotNull @Override protected PlotManager createManager() {
return new HybridPlotManager(this);
@Nonnull @Override protected PlotManager createManager() {
return new HybridPlotManager(this, this.regionManager);
}
public Location getSignLocation(Plot plot) {
public Location getSignLocation(@Nonnull Plot plot) {
plot = plot.getBasePlot(false);
Location bot = plot.getBottomAbs();
final Location bot = plot.getBottomAbs();
if (SIGN_LOCATION == null) {
bot.setY(ROAD_HEIGHT + 1);
return bot.add(-1, 0, -2);
return bot.withY(ROAD_HEIGHT + 1).add(-1, 0, -2);
} else {
bot.setY(0);
return bot.add(SIGN_LOCATION.getX(), SIGN_LOCATION.getY(), SIGN_LOCATION.getZ());
return bot.withY(0).add(SIGN_LOCATION.getX(), SIGN_LOCATION.getY(), SIGN_LOCATION.getZ());
}
}
@ -160,13 +181,11 @@ public class HybridPlotWorld extends ClassicPlotWorld {
setupSchematics();
} catch (Exception event) {
event.printStackTrace();
PlotSquared.debug("&c - road schematics are disabled for this world.");
}
// Dump world settings
if (Settings.DEBUG) {
PlotSquared.debug(String.format("- Dumping settings for ClassicPlotWorld with name %s",
this.getWorldName()));
logger.info("[P2] - Dumping settings for ClassicPlotWorld with name {}", this.getWorldName());
final Field[] fields = this.getClass().getFields();
for (final Field field : fields) {
final String name = field.getName().toLowerCase(Locale.ENGLISH);
@ -182,12 +201,12 @@ public class HybridPlotWorld extends ClassicPlotWorld {
} catch (final IllegalAccessException e) {
value = String.format("Failed to parse: %s", e.getMessage());
}
PlotSquared.debug(String.format("-- %s = %s", name, value));
logger.info("[P2] -- {} = {}", name, value);
}
}
}
@Override public boolean isCompatible(PlotArea plotArea) {
@Override public boolean isCompatible(@Nonnull final PlotArea plotArea) {
if (!(plotArea instanceof SquarePlotWorld)) {
return false;
}
@ -200,9 +219,9 @@ public class HybridPlotWorld extends ClassicPlotWorld {
// Try to determine root. This means that plot areas can have separate schematic
// directories
if (!(root = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" +
if (!(root = MainUtil.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" +
this.getWorldName() + "/" + this.getId())).exists()) {
root = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(),
root = MainUtil.getFile(PlotSquared.platform().getDirectory(),
"schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName());
}
@ -215,9 +234,9 @@ public class HybridPlotWorld extends ClassicPlotWorld {
File schematic3File = new File(root, "plot.schem");
if (!schematic3File.exists())
schematic3File = new File(root, "plot.schematic");
Schematic schematic1 = SchematicHandler.manager.getSchematic(schematic1File);
Schematic schematic2 = SchematicHandler.manager.getSchematic(schematic2File);
Schematic schematic3 = SchematicHandler.manager.getSchematic(schematic3File);
Schematic schematic1 = this.schematicHandler.getSchematic(schematic1File);
Schematic schematic2 = this.schematicHandler.getSchematic(schematic2File);
Schematic schematic3 = this.schematicHandler.getSchematic(schematic3File);
int shift = this.ROAD_WIDTH / 2;
int oddshift = (this.ROAD_WIDTH & 1) == 0 ? 0 : 1;
@ -282,10 +301,14 @@ public class HybridPlotWorld extends ClassicPlotWorld {
}
}
PlotSquared.debug(Captions.PREFIX + "&3 - plot schematic: &7" + schematic3File.getPath());
if (Settings.DEBUG) {
logger.info("[P2] - plot schematic: {}", schematic3File.getPath());
}
}
if (schematic1 == null || schematic2 == null || this.ROAD_WIDTH == 0) {
PlotSquared.debug(Captions.PREFIX + "&3 - schematic: &7false");
if (Settings.DEBUG) {
logger.info("[P2] - schematic: false");
}
return;
}
this.ROAD_SCHEMATIC_ENABLED = true;
@ -361,7 +384,7 @@ public class HybridPlotWorld extends ClassicPlotWorld {
int pair = MathMan.pair(x, z);
BaseBlock[] existing = this.G_SCH.computeIfAbsent(pair, k -> new BaseBlock[height]);
if (y >= height) {
PlotSquared.log("Error adding overlay block. `y > height` ");
logger.error("[P2] Error adding overlay block. `y > height`");
return;
}
existing[y] = id;

View File

@ -25,6 +25,7 @@
*/
package com.plotsquared.core.generator;
import com.google.inject.Inject;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.events.PlotFlagAddEvent;
@ -40,6 +41,7 @@ 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.flag.implementations.AnalysisFlag;
import com.plotsquared.core.plot.world.PlotAreaManager;
import com.plotsquared.core.queue.ChunkBlockQueue;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.queue.LocalBlockQueue;
@ -61,6 +63,9 @@ import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.util.ArrayDeque;
@ -74,7 +79,9 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class HybridUtils {
public class HybridUtils {
private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName());
public static HybridUtils manager;
public static Set<BlockVector2> regions;
@ -83,9 +90,27 @@ public abstract class HybridUtils {
public static PlotArea area;
public static boolean UPDATE = false;
public static boolean regeneratePlotWalls(final PlotArea area) {
private final PlotAreaManager plotAreaManager;
private final ChunkManager chunkManager;
private final GlobalBlockQueue blockQueue;
private final WorldUtil worldUtil;
private final RegionManager regionManager;
private final SchematicHandler schematicHandler;
@Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager,
@Nonnull final ChunkManager chunkManager, @Nonnull final GlobalBlockQueue blockQueue,
@Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, @Nonnull final SchematicHandler schematicHandler) {
this.plotAreaManager = plotAreaManager;
this.chunkManager = chunkManager;
this.blockQueue = blockQueue;
this.worldUtil = worldUtil;
this.regionManager = regionManager;
this.schematicHandler = schematicHandler;
}
public void regeneratePlotWalls(final PlotArea area) {
PlotManager plotManager = area.getPlotManager();
return plotManager.regenerateAllPlotWalls();
plotManager.regenerateAllPlotWalls();
}
public void analyzeRegion(final String world, final CuboidRegion region,
@ -103,7 +128,7 @@ public abstract class HybridUtils {
*
*/
TaskManager.runTaskAsync(() -> {
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final LocalBlockQueue queue = blockQueue.getNewQueue(world, false);
final BlockVector3 bot = region.getMinimumPoint();
final BlockVector3 top = region.getMaximumPoint();
@ -120,7 +145,7 @@ public abstract class HybridUtils {
final int width = tx - bx + 1;
final int length = tz - bz + 1;
PlotArea area = PlotSquared.get().getPlotArea(world, null);
final PlotArea area = this.plotAreaManager.getPlotArea(world, null);
if (!(area instanceof HybridPlotWorld)) {
return;
@ -227,8 +252,8 @@ public abstract class HybridUtils {
});
System.gc();
MainUtil.initCache();
Location botLoc = new Location(world, bot.getX(), bot.getY(), bot.getZ());
Location topLoc = new Location(world, top.getX(), top.getY(), top.getZ());
Location botLoc = Location.at(world, bot.getX(), bot.getY(), bot.getZ());
Location topLoc = Location.at(world, top.getX(), top.getY(), top.getZ());
ChunkManager.chunkTask(botLoc, topLoc, new RunnableVal<int[]>() {
@Override public void run(int[] value) {
int X = value[0];
@ -357,7 +382,7 @@ public abstract class HybridUtils {
for (int z = z1; z <= z2; z++) {
BlockState block = queue.getBlock(x, y, z);
boolean same =
Arrays.stream(blocks).anyMatch(p -> WorldUtil.IMP.isBlockSame(block, p));
Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p));
if (!same) {
count++;
}
@ -384,7 +409,7 @@ public abstract class HybridUtils {
return false;
}
HybridUtils.UPDATE = true;
Set<BlockVector2> regions = RegionManager.manager.getChunkChunks(area.getWorldName());
Set<BlockVector2> regions = this.regionManager.getChunkChunks(area.getWorldName());
return scheduleRoadUpdate(area, regions, extend, new HashSet<>());
}
@ -413,24 +438,25 @@ public abstract class HybridUtils {
BlockVector2 chunk = iter.next();
iter.remove();
boolean regenedRoad = regenerateRoad(area, chunk, extend);
if (!regenedRoad) {
PlotSquared.debug("Failed to regenerate roads.");
if (!regenedRoad && Settings.DEBUG) {
logger.info("[P2] Failed to regenerate roads");
}
ChunkManager.manager.unloadChunk(area.getWorldName(), chunk, true);
chunkManager.unloadChunk(area.getWorldName(), chunk, true);
}
if (Settings.DEBUG) {
logger.info("[P2] Cancelled road task");
}
PlotSquared.debug("Cancelled road task");
return;
}
count.incrementAndGet();
if (count.intValue() % 20 == 0) {
PlotSquared.debug("PROGRESS: " + 100 * (2048 - chunks.size()) / 2048 + "%");
logger.info("[P2] Progress: {}%", 100 * (2048 - chunks.size()) / 2048);
}
if (HybridUtils.regions.isEmpty() && chunks.isEmpty()) {
PlotSquared.debug("Regenerating plot walls");
regeneratePlotWalls(area);
HybridUtils.UPDATE = false;
PlotSquared.log("Finished road conversion");
logger.info("[P2] Finished road conversion");
// CANCEL TASK
} else {
final Runnable task = this;
@ -442,17 +468,17 @@ public abstract class HybridUtils {
HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next();
iterator.remove();
PlotSquared.debug(
"Updating .mcr: " + loc.getX() + ", " + loc.getZ()
+ " (approx 1024 chunks)");
PlotSquared
.debug(" - Remaining: " + HybridUtils.regions.size());
if (Settings.DEBUG) {
logger.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)",
loc.getX(), loc.getZ());
logger.info("[P2] - Remaining: {}", HybridUtils.regions.size());
}
chunks.addAll(getChunks(loc));
System.gc();
}
}
if (!chunks.isEmpty()) {
TaskManager.IMP.sync(new RunnableVal<Object>() {
TaskManager.getImplementation().sync(new RunnableVal<Object>() {
@Override public void run(Object value) {
long start = System.currentTimeMillis();
Iterator<BlockVector2> iterator = chunks.iterator();
@ -462,8 +488,8 @@ public abstract class HybridUtils {
iterator.remove();
boolean regenedRoads =
regenerateRoad(area, chunk, extend);
if (!regenedRoads) {
PlotSquared.debug("Failed to regenerate road.");
if (!regenedRoads && Settings.DEBUG) {
logger.info("[P2] Failed to regenerate road");
}
}
}
@ -474,22 +500,18 @@ public abstract class HybridUtils {
Iterator<BlockVector2> iterator = HybridUtils.regions.iterator();
BlockVector2 loc = iterator.next();
iterator.remove();
PlotSquared.debug(
"[ERROR] Could not update '" + area.getWorldName() + "/region/r."
+ loc.getX() + "." + loc.getZ() + ".mca' (Corrupt chunk?)");
logger.error("[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)",
area.getWorldHash(), loc.getX(), loc.getZ());
int sx = loc.getX() << 5;
int sz = loc.getZ() << 5;
for (int x = sx; x < sx + 32; x++) {
for (int z = sz; z < sz + 32; z++) {
ChunkManager.manager
.unloadChunk(area.getWorldName(), BlockVector2.at(x, z),
chunkManager.unloadChunk(area.getWorldName(), BlockVector2.at(x, z),
true);
}
}
PlotSquared.debug(" - Potentially skipping 1024 chunks");
PlotSquared.debug(" - TODO: recommend chunkster if corrupt");
}
GlobalBlockQueue.IMP.addEmptyTask(() -> TaskManager.runTaskLater(task, 20));
blockQueue.addEmptyTask(() -> TaskManager.runTaskLater(task, 20));
});
}
}
@ -499,7 +521,7 @@ public abstract class HybridUtils {
public boolean setupRoadSchematic(Plot plot) {
final String world = plot.getWorldName();
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final LocalBlockQueue queue = blockQueue.getNewQueue(world, false);
Location bot = plot.getBottomAbs().subtract(1, 0, 1);
Location top = plot.getTopAbs();
final HybridPlotWorld plotworld = (HybridPlotWorld) plot.getArea();
@ -523,13 +545,12 @@ public abstract class HybridUtils {
"schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea()
.toString() + File.separator;
SchematicHandler.manager.getCompoundTag(world, sideRoad, new RunnableVal<CompoundTag>() {
this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal<CompoundTag>() {
@Override public void run(CompoundTag value) {
SchematicHandler.manager.save(value, dir + "sideroad.schem");
SchematicHandler.manager
.getCompoundTag(world, intersection, new RunnableVal<CompoundTag>() {
schematicHandler.save(value, dir + "sideroad.schem");
schematicHandler.getCompoundTag(world, intersection, new RunnableVal<CompoundTag>() {
@Override public void run(CompoundTag value) {
SchematicHandler.manager.save(value, dir + "intersection.schem");
schematicHandler.save(value, dir + "intersection.schem");
plotworld.ROAD_SCHEMATIC_ENABLED = true;
try {
plotworld.setupSchematics();
@ -587,9 +608,9 @@ public abstract class HybridUtils {
z -= plotWorld.ROAD_OFFSET_Z;
final int finalX = x;
final int finalZ = z;
LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(plotWorld.getWorldName(), false);
LocalBlockQueue queue = this.blockQueue.getNewQueue(plotWorld.getWorldName(), false);
if (id1 == null || id2 == null || id1 != id2) {
ChunkManager.manager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> {
this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> {
if (id1 != null) {
Plot p1 = area.getPlotAbs(id1);
if (p1 != null && p1.hasOwner() && p1.isMerged()) {

View File

@ -31,7 +31,6 @@ import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.plot.SetupObject;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import com.plotsquared.core.setup.PlotAreaBuilder;
import com.plotsquared.core.setup.SetupProcess;
/**
* This class allows for implementation independent world generation.
@ -104,7 +103,7 @@ public abstract class IndependentPlotGenerator {
* @return
*/
public <T> GeneratorWrapper<T> specify(String world) {
return (GeneratorWrapper<T>) PlotSquared.get().IMP.wrapPlotGenerator(world, this);
return (GeneratorWrapper<T>) PlotSquared.platform().wrapPlotGenerator(world, this);
}
@Override public String toString() {

View File

@ -25,23 +25,32 @@
*/
package com.plotsquared.core.generator;
import com.plotsquared.core.PlotSquared;
import com.google.inject.Inject;
import com.plotsquared.core.location.Location;
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.plot.world.SinglePlotAreaManager;
import com.plotsquared.core.queue.ScopedLocalBlockQueue;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockTypes;
import javax.annotation.Nonnull;
public class SingleWorldGenerator extends IndependentPlotGenerator {
private Location bedrock1 = new Location(null, 0, 0, 0);
private Location bedrock2 = new Location(null, 15, 0, 15);
private Location dirt1 = new Location(null, 0, 1, 0);
private Location dirt2 = new Location(null, 15, 2, 15);
private Location grass1 = new Location(null, 0, 3, 0);
private Location grass2 = new Location(null, 15, 3, 15);
private static final Location bedrock1 = Location.at("", 0, 0, 0);
private static final Location bedrock2 = Location.at("", 15, 0, 15);
private static final Location dirt1 = Location.at("", 0, 1, 0);
private static final Location dirt2 = Location.at("", 15, 2, 15);
private static final Location grass1 = Location.at("", 0, 3, 0);
private static final Location grass2 = Location.at("", 15, 3, 15);
private final PlotAreaManager plotAreaManager;
@Inject public SingleWorldGenerator(@Nonnull final PlotAreaManager plotAreaManager) {
this.plotAreaManager = plotAreaManager;
}
@Override public String getName() {
return "PlotSquared:single";
@ -63,10 +72,10 @@ public class SingleWorldGenerator extends IndependentPlotGenerator {
}
@Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return ((SinglePlotAreaManager) PlotSquared.get().getPlotAreaManager()).getArea();
return ((SinglePlotAreaManager) this.plotAreaManager).getArea();
}
@Override public void initialize(PlotArea area) {
}
}

View File

@ -25,7 +25,6 @@
*/
package com.plotsquared.core.generator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.location.Direction;
import com.plotsquared.core.location.Location;
import com.plotsquared.core.plot.Plot;
@ -34,8 +33,10 @@ import com.plotsquared.core.plot.PlotId;
import com.plotsquared.core.util.MainUtil;
import com.plotsquared.core.util.RegionManager;
import com.sk89q.worldedit.regions.CuboidRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
@ -44,11 +45,15 @@ import java.util.Set;
*/
public abstract class SquarePlotManager extends GridPlotManager {
private final SquarePlotWorld squarePlotWorld;
private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName());
public SquarePlotManager(SquarePlotWorld squarePlotWorld) {
private final SquarePlotWorld squarePlotWorld;
private final RegionManager regionManager;
public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, @Nonnull final RegionManager regionManager) {
super(squarePlotWorld);
this.squarePlotWorld = squarePlotWorld;
this.regionManager = regionManager;
}
@Override public boolean clearPlot(final Plot plot, final Runnable whenDone) {
@ -62,11 +67,9 @@ public abstract class SquarePlotManager extends GridPlotManager {
Iterator<CuboidRegion> iterator = regions.iterator();
CuboidRegion region = iterator.next();
iterator.remove();
Location pos1 = new Location(plot.getWorldName(), region.getMinimumPoint().getX(),
region.getMinimumPoint().getY(), region.getMinimumPoint().getZ());
Location pos2 = new Location(plot.getWorldName(), region.getMaximumPoint().getX(),
region.getMaximumPoint().getY(), region.getMaximumPoint().getZ());
RegionManager.manager.regenerateRegion(pos1, pos2, false, this);
final Location pos1 = Location.at(plot.getWorldName(), region.getMinimumPoint());
final Location pos2 = Location.at(plot.getWorldName(), region.getMaximumPoint());
regionManager.regenerateRegion(pos1, pos2, false, this);
}
};
run.run();
@ -80,7 +83,7 @@ public abstract class SquarePlotManager extends GridPlotManager {
+ squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1;
int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH
+ squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1;
return new Location(squarePlotWorld.getWorldName(), x, Math.min(getWorldHeight(), 255), z);
return Location.at(squarePlotWorld.getWorldName(), x, Math.min(getWorldHeight(), 255), z);
}
@Override public PlotId getPlotIdAbs(int x, int y, int z) {
@ -226,11 +229,9 @@ public abstract class SquarePlotManager extends GridPlotManager {
// northwest
return plot.getMerged(Direction.NORTHWEST) ? id : null;
}
PlotSquared.debug("invalid location: " + Arrays.toString(merged));
} catch (Exception ignored) {
PlotSquared.debug(
"Invalid plot / road width in settings.yml for world: " + squarePlotWorld
.getWorldName());
logger.error( "Invalid plot / road width in settings.yml for world: {}", squarePlotWorld
.getWorldName());
}
return null;
}
@ -247,7 +248,6 @@ public abstract class SquarePlotManager extends GridPlotManager {
int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH
+ squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math
.floor(squarePlotWorld.ROAD_WIDTH / 2);
return new Location(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(),
z);
return Location.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z);
}
}

View File

@ -25,26 +25,44 @@
*/
package com.plotsquared.core.generator;
import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.configuration.ConfigurationSection;
import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.configuration.file.YamlConfiguration;
import com.plotsquared.core.inject.annotations.WorldConfig;
import com.plotsquared.core.plot.PlotId;
import org.jetbrains.annotations.NotNull;
import com.plotsquared.core.queue.GlobalBlockQueue;
import com.plotsquared.core.util.EconHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SquarePlotWorld extends GridPlotWorld {
private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotWorld.class.getSimpleName());
public int PLOT_WIDTH = 42;
public int ROAD_WIDTH = 7;
public int ROAD_OFFSET_X = 0;
public int ROAD_OFFSET_Z = 0;
public SquarePlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator,
PlotId min, PlotId max) {
super(worldName, id, generator, min, max);
public SquarePlotWorld(final String worldName,
@Nullable final String id,
@Nonnull final IndependentPlotGenerator generator,
@Nullable final PlotId min,
@Nullable final PlotId max,
@WorldConfig @Nonnull final YamlConfiguration worldConfiguration,
@Nonnull final GlobalBlockQueue blockQueue,
@Nullable final EconHandler econHandler) {
super(worldName, id, generator, min, max, worldConfiguration, blockQueue, econHandler);
}
@Override public void loadConfiguration(ConfigurationSection config) {
if (!config.contains("plot.height")) {
PlotSquared.debug(" - &cConfiguration is null? (" + config.getCurrentPath() + ')');
if (Settings.DEBUG) {
logger.info("[P2] - Configuration is null? ({})", config.getCurrentPath());
}
}
this.PLOT_WIDTH = config.getInt("plot.size");
this.ROAD_WIDTH = config.getInt("road.width");

View File

@ -0,0 +1,39 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.inject.annotations;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface BackgroundPipeline {
}

View File

@ -0,0 +1,39 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.inject.annotations;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface ConfigFile {
}

View File

@ -0,0 +1,39 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.inject.annotations;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface ConsoleActor {
}

View File

@ -0,0 +1,39 @@
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2020 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.inject.annotations;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
public @interface DefaultGenerator {
}

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