Permalink
Browse files

Start work on abstracting commands out of worldedit-legacy

  • Loading branch information...
me4502 committed Dec 10, 2018
1 parent 80aec37 commit 947f6ee0969b658849b203c6ec0612ef3ad3f2e7
Showing with 531 additions and 616 deletions.
  1. +51 −0 worldguard-core/src/main/java/com/sk89q/worldguard/WorldGuard.java
  2. +177 −0 worldguard-core/src/main/java/com/sk89q/worldguard/session/AbstractSessionManager.java
  3. +1 −1 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/BukkitWorldGuardPlatform.java
  4. +8 −42 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardPlugin.java
  5. +13 −14 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/AsyncCommandHelper.java
  6. +7 −6 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/CommandUtils.java
  7. +5 −5 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/FutureProgressListener.java
  8. +44 −49 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/GeneralCommands.java
  9. +20 −21 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/MessageFutureCallback.java
  10. +6 −6 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/MessageTimerTask.java
  11. +9 −10 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/ProtectionCommands.java
  12. +8 −9 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/ToggleCommands.java
  13. +33 −37 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/WorldGuardCommands.java
  14. +29 −33 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/region/MemberCommands.java
  15. +89 −107 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommands.java
  16. +19 −25 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionCommandsBase.java
  17. +4 −4 ...guard-legacy/src/main/java/com/sk89q/worldguard/bukkit/commands/region/RegionPrintoutBuilder.java
  18. +4 −243 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/session/BukkitSessionManager.java
  19. +4 −4 worldguard-legacy/src/main/java/com/sk89q/worldguard/bukkit/util/logging/LoggerToChatHandler.java
@@ -24,6 +24,7 @@
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.squirrelid.cache.HashMapCache;
import com.sk89q.squirrelid.cache.ProfileCache;
import com.sk89q.squirrelid.cache.SQLiteCache;
@@ -32,10 +33,13 @@
import com.sk89q.squirrelid.resolver.CombinedProfileService;
import com.sk89q.squirrelid.resolver.HttpRepositoryService;
import com.sk89q.squirrelid.resolver.ProfileService;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldguard.internal.platform.WorldGuardPlatform;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.util.UnresolvedNamesException;
import com.sk89q.worldguard.util.concurrent.EvenMoreExecutors;
import com.sk89q.worldguard.util.task.SimpleSupervisor;
import com.sk89q.worldguard.util.task.Supervisor;
@@ -44,11 +48,15 @@
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Nullable;

public class WorldGuard {

public static final Logger logger = Logger.getLogger(WorldGuard.class.getCanonicalName());
@@ -152,6 +160,49 @@ public ProfileCache getProfileCache() {
return profileCache;
}

/**
* Checks to see if the sender is a player, otherwise throw an exception.
*
* @param sender The sender
* @return The player
* @throws CommandException if it isn't a player
*/
public LocalPlayer checkPlayer(Actor sender) throws CommandException {
if (sender instanceof LocalPlayer) {
return (LocalPlayer) sender;
} else {
throw new CommandException("A player is expected.");
}
}

/**
* Convert the throwable into a somewhat friendly message.
*
* @param throwable the throwable
* @return a message
*/
public String convertThrowable(@Nullable Throwable throwable) {
if (throwable instanceof NumberFormatException) {
return "Number expected, string received instead.";
} else if (throwable instanceof StorageException) {
WorldGuard.logger.log(Level.WARNING, "Error loading/saving regions", throwable);
return "Region data could not be loaded/saved: " + throwable.getMessage();
} else if (throwable instanceof RejectedExecutionException) {
return "There are currently too many tasks queued to add yours. Use /wg running to list queued and running tasks.";
} else if (throwable instanceof CancellationException) {
return "WorldGuard: Task was cancelled";
} else if (throwable instanceof InterruptedException) {
return "WorldGuard: Task was interrupted";
} else if (throwable instanceof UnresolvedNamesException) {
return throwable.getMessage();
} else if (throwable instanceof CommandException) {
return throwable.getMessage();
} else {
WorldGuard.logger.log(Level.WARNING, "WorldGuard encountered an unexpected error", throwable);
return "WorldGuard: An unexpected error occurred! Please see the server console.";
}
}

/**
* Called when WorldGuard should be disabled.
*/
@@ -0,0 +1,177 @@
package com.sk89q.worldguard.session;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.session.handler.EntryFlag;
import com.sk89q.worldguard.session.handler.ExitFlag;
import com.sk89q.worldguard.session.handler.FarewellFlag;
import com.sk89q.worldguard.session.handler.FeedFlag;
import com.sk89q.worldguard.session.handler.GameModeFlag;
import com.sk89q.worldguard.session.handler.GodMode;
import com.sk89q.worldguard.session.handler.GreetingFlag;
import com.sk89q.worldguard.session.handler.Handler;
import com.sk89q.worldguard.session.handler.HealFlag;
import com.sk89q.worldguard.session.handler.InvincibilityFlag;
import com.sk89q.worldguard.session.handler.NotifyEntryFlag;
import com.sk89q.worldguard.session.handler.NotifyExitFlag;
import com.sk89q.worldguard.session.handler.TimeLockFlag;
import com.sk89q.worldguard.session.handler.WaterBreathing;
import com.sk89q.worldguard.session.handler.WeatherLockFlag;

import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class AbstractSessionManager implements SessionManager {

public static final int RUN_DELAY = 20;
public static final long SESSION_LIFETIME = 10;

private final LoadingCache<WorldPlayerTuple, Boolean> bypassCache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(2, TimeUnit.SECONDS)
.build(new CacheLoader<WorldPlayerTuple, Boolean>() {
@Override
public Boolean load(@Nonnull WorldPlayerTuple tuple) throws Exception {
return tuple.getPlayer().hasPermission("worldguard.region.bypass." + tuple.getWorld().getName());
}
});

private final LoadingCache<CacheKey, Session> sessions = CacheBuilder.newBuilder()
.expireAfterAccess(SESSION_LIFETIME, TimeUnit.MINUTES)
.build(new CacheLoader<CacheKey, Session>() {
@Override
public Session load(@Nonnull CacheKey key) throws Exception {
return createSession(key.playerRef.get());
}
});

private LinkedList<Handler.Factory<? extends Handler>> handlers = new LinkedList<>();

private static final Set<Handler.Factory<? extends Handler>> defaultHandlers = new HashSet<>();
static {
Handler.Factory<?>[] factories = {
HealFlag.FACTORY,
FeedFlag.FACTORY,
NotifyEntryFlag.FACTORY,
NotifyExitFlag.FACTORY,
EntryFlag.FACTORY,
ExitFlag.FACTORY,
FarewellFlag.FACTORY,
GreetingFlag.FACTORY,
GameModeFlag.FACTORY,
InvincibilityFlag.FACTORY,
TimeLockFlag.FACTORY,
WeatherLockFlag.FACTORY,
GodMode.FACTORY,
WaterBreathing.FACTORY
};
defaultHandlers.addAll(Arrays.asList(factories));
}

public AbstractSessionManager() {
handlers.addAll(defaultHandlers);
}


@Override
public boolean registerHandler(Handler.Factory<? extends Handler> factory, @Nullable Handler.Factory<? extends Handler> after) {
if (factory == null) return false;
WorldGuard.logger.log(Level.INFO, "Registering session handler "
+ factory.getClass().getEnclosingClass().getName());
if (after == null) {
handlers.add(factory);
} else {
int index = handlers.indexOf(after);
if (index == -1) return false;

handlers.add(index, factory); // shifts "after" right one, and everything after "after" right one
}
return true;
}

@Override
public boolean unregisterHandler(Handler.Factory<? extends Handler> factory) {
if (defaultHandlers.contains(factory)) {
WorldGuard.logger.log(Level.WARNING, "Someone is unregistering a default WorldGuard handler: "
+ factory.getClass().getEnclosingClass().getName() + ". This may cause parts of WorldGuard to stop functioning");
} else {
WorldGuard.logger.log(Level.INFO, "Unregistering session handler "
+ factory.getClass().getEnclosingClass().getName());
}
return handlers.remove(factory);
}

@Override
public boolean hasBypass(LocalPlayer player, World world) {
return bypassCache.getUnchecked(new WorldPlayerTuple(world, player));
}

@Override
public void resetState(LocalPlayer player) {
checkNotNull(player, "player");
@Nullable Session session = sessions.getIfPresent(new CacheKey(player));
if (session != null) {
session.resetState(player);
}
}

@Override
@Nullable
public Session getIfPresent(LocalPlayer player) {
return sessions.getIfPresent(player);
}

@Override
public Session get(LocalPlayer player) {
return sessions.getUnchecked(new CacheKey(player));
}

@Override
public Session createSession(LocalPlayer player) {
Session session = new Session(this);
for (Handler.Factory<? extends Handler> factory : handlers) {
session.register(factory.create(session));
}
session.initialize(player);
return session;
}

protected static final class CacheKey {
final WeakReference<LocalPlayer> playerRef;
final UUID uuid;

CacheKey(LocalPlayer player) {
playerRef = new WeakReference<>(player);
uuid = player.getUniqueId();
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
return uuid.equals(cacheKey.uuid);

}

@Override
public int hashCode() {
return uuid.hashCode();
}
}
}
@@ -107,7 +107,7 @@ public void broadcastNotification(String message) {

@Override
public void load() {
sessionManager = new BukkitSessionManager(WorldGuardPlugin.inst());
sessionManager = new BukkitSessionManager();
configuration = new BukkitConfigurationManager(WorldGuardPlugin.inst());
configuration.load();
regionContainer = new BukkitRegionContainer(WorldGuardPlugin.inst());
@@ -66,10 +66,8 @@
import com.sk89q.worldguard.bukkit.util.logging.ClassSourceValidator;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.registry.SimpleFlagRegistry;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.util.UnresolvedNamesException;
import com.sk89q.worldguard.util.logging.RecordMessagePrefixer;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
@@ -94,35 +92,30 @@
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.RejectedExecutionException;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;

import javax.annotation.Nullable;

/**
* The main class for WorldGuard as a Bukkit plugin.
*/
public class WorldGuardPlugin extends JavaPlugin {

private static WorldGuardPlugin inst;
private static BukkitWorldGuardPlatform platform;
private final CommandsManager<CommandSender> commands;
private final CommandsManager<Actor> commands;
private PlayerMoveListener playerMoveListener;

/**
* Construct objects. Actual loading occurs when the plugin is enabled, so
* this merely instantiates the objects.
*/
public WorldGuardPlugin() {
final WorldGuardPlugin plugin = inst = this;
commands = new CommandsManager<CommandSender>() {
inst = this;
commands = new CommandsManager<Actor>() {
@Override
public boolean hasPermission(CommandSender player, String perm) {
return plugin.hasPermission(player, perm);
public boolean hasPermission(Actor player, String perm) {
return player.hasPermission(perm);
}
};
}
@@ -234,7 +227,8 @@ public void onDisable() {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
try {
commands.execute(cmd.getName(), args, sender, sender);
Actor actor = wrapCommandSender(sender);
commands.execute(cmd.getName(), args, actor, actor);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatColor.RED + "You don't have permission.");
} catch (MissingNestedCommandException e) {
@@ -243,42 +237,14 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String
sender.sendMessage(ChatColor.RED + e.getMessage());
sender.sendMessage(ChatColor.RED + e.getUsage());
} catch (WrappedCommandException e) {
sender.sendMessage(ChatColor.RED + convertThrowable(e.getCause()));
sender.sendMessage(ChatColor.RED + WorldGuard.getInstance().convertThrowable(e.getCause()));
} catch (CommandException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}

return true;
}

/**
* Convert the throwable into a somewhat friendly message.
*
* @param throwable the throwable
* @return a message
*/
public String convertThrowable(@Nullable Throwable throwable) {
if (throwable instanceof NumberFormatException) {
return "Number expected, string received instead.";
} else if (throwable instanceof StorageException) {
WorldGuard.logger.log(Level.WARNING, "Error loading/saving regions", throwable);
return "Region data could not be loaded/saved: " + throwable.getMessage();
} else if (throwable instanceof RejectedExecutionException) {
return "There are currently too many tasks queued to add yours. Use /wg running to list queued and running tasks.";
} else if (throwable instanceof CancellationException) {
return "WorldGuard: Task was cancelled";
} else if (throwable instanceof InterruptedException) {
return "WorldGuard: Task was interrupted";
} else if (throwable instanceof UnresolvedNamesException) {
return throwable.getMessage();
} else if (throwable instanceof CommandException) {
return throwable.getMessage();
} else {
WorldGuard.logger.log(Level.WARNING, "WorldGuard encountered an unexpected error", throwable);
return "WorldGuard: An unexpected error occurred! Please see the server console.";
}
}

/**
* Check whether a player is in a group.
* This calls the corresponding method in PermissionsResolverManager
Oops, something went wrong.

0 comments on commit 947f6ee

Please sign in to comment.