More cleanup

This commit is contained in:
Luck 2016-11-08 20:46:29 +00:00
parent 90f8dbe243
commit 1c534d7475
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
31 changed files with 223 additions and 169 deletions

View File

@ -25,7 +25,6 @@ package me.lucko.luckperms.bukkit;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.api.data.Callback;
import me.lucko.luckperms.common.LuckPermsPlugin;
import me.lucko.luckperms.common.commands.CommandManager; import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.Util; import me.lucko.luckperms.common.commands.Util;
import me.lucko.luckperms.common.constants.Patterns; import me.lucko.luckperms.common.constants.Patterns;
@ -38,14 +37,17 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
class BukkitCommand extends CommandManager implements CommandExecutor, TabExecutor { class BukkitCommand extends CommandManager implements CommandExecutor, TabExecutor {
BukkitCommand(LuckPermsPlugin plugin) { private final LPBukkitPlugin plugin;
BukkitCommand(LPBukkitPlugin plugin) {
super(plugin); super(plugin);
this.plugin = plugin;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
onCommand( onCommand(
BukkitSenderFactory.get(getPlugin()).wrap(sender), plugin.getSenderFactory().wrap(sender),
label, label,
Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))), Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))),
Callback.empty() Callback.empty()
@ -53,9 +55,8 @@ class BukkitCommand extends CommandManager implements CommandExecutor, TabExecut
return true; return true;
} }
@Override @Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
return onTabComplete(BukkitSenderFactory.get(getPlugin()).wrap(sender), Arrays.asList(args)); return onTabComplete(plugin.getSenderFactory().wrap(sender), Arrays.asList(args));
} }
} }

View File

@ -31,19 +31,10 @@ import org.bukkit.entity.Player;
import java.util.UUID; import java.util.UUID;
public class BukkitSenderFactory extends SenderFactory<CommandSender> { public class BukkitSenderFactory extends SenderFactory<CommandSender> {
private static BukkitSenderFactory instance = null; public BukkitSenderFactory(LuckPermsPlugin plugin) {
private BukkitSenderFactory(LuckPermsPlugin plugin) {
super(plugin); super(plugin);
} }
public static synchronized BukkitSenderFactory get(LuckPermsPlugin plugin) {
if (instance == null) {
instance = new BukkitSenderFactory(plugin);
}
return instance;
}
@Override @Override
protected String getName(CommandSender sender) { protected String getName(CommandSender sender) {
if (sender instanceof Player) { if (sender instanceof Player) {

View File

@ -97,6 +97,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
private BufferedRequest<Void> updateTaskBuffer; private BufferedRequest<Void> updateTaskBuffer;
private boolean started = false; private boolean started = false;
private DebugHandler debugHandler; private DebugHandler debugHandler;
private BukkitSenderFactory senderFactory;
private ExecutorService executorService; private ExecutorService executorService;
private boolean schedulerAvailable = false; private boolean schedulerAvailable = false;
@ -108,6 +109,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
log = LogFactory.wrap(getLogger()); log = LogFactory.wrap(getLogger());
debugHandler = new DebugHandler(); debugHandler = new DebugHandler();
senderFactory = new BukkitSenderFactory(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new BukkitConfig(this); configuration = new BukkitConfig(this);
@ -319,16 +321,15 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getNotifyListeners() { public List<Sender> getSenders() {
return getServer().getOnlinePlayers().stream() return getServer().getOnlinePlayers().stream()
.map(p -> BukkitSenderFactory.get(this).wrap(p)) .map(p -> getSenderFactory().wrap(p))
.filter(Permission.LOG_NOTIFY::isAuthorized)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public Sender getConsoleSender() { public Sender getConsoleSender() {
return BukkitSenderFactory.get(this).wrap(getServer().getConsoleSender()); return getSenderFactory().wrap(getServer().getConsoleSender());
} }
@Override @Override

View File

@ -184,7 +184,7 @@ public class LPPermissible extends PermissibleBase {
} }
PermissionAttachment result = addAttachment(plugin); PermissionAttachment result = addAttachment(plugin);
if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RemoveAttachmentRunnable(result), ticks) == -1) { if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> result.remove(), ticks) == -1) {
Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1"); Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1");
result.remove(); result.remove();
return null; return null;
@ -254,16 +254,4 @@ public class LPPermissible extends PermissibleBase {
} }
} }
} }
private class RemoveAttachmentRunnable implements Runnable {
private PermissionAttachment attachment;
private RemoveAttachmentRunnable(PermissionAttachment attachment) {
this.attachment = attachment;
}
public void run() {
attachment.remove();
}
}
} }

View File

@ -35,17 +35,19 @@ import net.md_5.bungee.api.plugin.TabExecutor;
import java.util.Arrays; import java.util.Arrays;
class BungeeCommand extends Command implements TabExecutor { class BungeeCommand extends Command implements TabExecutor {
private final LPBungeePlugin plugin;
private final CommandManager manager; private final CommandManager manager;
BungeeCommand(CommandManager manager) { BungeeCommand(LPBungeePlugin plugin, CommandManager manager) {
super("luckpermsbungee", null, "bperms", "lpb", "bpermissions", "bp", "bperm"); super("luckpermsbungee", null, "bperms", "lpb", "bpermissions", "bp", "bperm");
this.plugin = plugin;
this.manager = manager; this.manager = manager;
} }
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
manager.onCommand( manager.onCommand(
BungeeSenderFactory.get(manager.getPlugin()).wrap(sender), plugin.getSenderFactory().wrap(sender),
"bperms", "bperms",
Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))), Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(Joiner.on(' ').join(args))),
Callback.empty() Callback.empty()
@ -54,6 +56,6 @@ class BungeeCommand extends Command implements TabExecutor {
@Override @Override
public Iterable<String> onTabComplete(CommandSender sender, String[] args) { public Iterable<String> onTabComplete(CommandSender sender, String[] args) {
return manager.onTabComplete(BungeeSenderFactory.get(manager.getPlugin()).wrap(sender), Arrays.asList(args)); return manager.onTabComplete(plugin.getSenderFactory().wrap(sender), Arrays.asList(args));
} }
} }

View File

@ -32,19 +32,10 @@ import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.UUID; import java.util.UUID;
public class BungeeSenderFactory extends SenderFactory<CommandSender> { public class BungeeSenderFactory extends SenderFactory<CommandSender> {
private static BungeeSenderFactory instance = null; public BungeeSenderFactory(LuckPermsPlugin plugin) {
private BungeeSenderFactory(LuckPermsPlugin plugin) {
super(plugin); super(plugin);
} }
public static synchronized BungeeSenderFactory get(LuckPermsPlugin plugin) {
if (instance == null) {
instance = new BungeeSenderFactory(plugin);
}
return instance;
}
@Override @Override
protected String getName(CommandSender sender) { protected String getName(CommandSender sender) {
if (sender instanceof ProxiedPlayer) { if (sender instanceof ProxiedPlayer) {

View File

@ -36,7 +36,6 @@ import me.lucko.luckperms.common.commands.CommandManager;
import me.lucko.luckperms.common.commands.ConsecutiveExecutor; import me.lucko.luckperms.common.commands.ConsecutiveExecutor;
import me.lucko.luckperms.common.commands.Sender; import me.lucko.luckperms.common.commands.Sender;
import me.lucko.luckperms.common.config.LPConfiguration; import me.lucko.luckperms.common.config.LPConfiguration;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.contexts.ContextManager; import me.lucko.luckperms.common.contexts.ContextManager;
import me.lucko.luckperms.common.contexts.ServerCalculator; import me.lucko.luckperms.common.contexts.ServerCalculator;
import me.lucko.luckperms.common.core.UuidCache; import me.lucko.luckperms.common.core.UuidCache;
@ -85,11 +84,13 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
private CalculatorFactory calculatorFactory; private CalculatorFactory calculatorFactory;
private BufferedRequest<Void> updateTaskBuffer; private BufferedRequest<Void> updateTaskBuffer;
private DebugHandler debugHandler; private DebugHandler debugHandler;
private BungeeSenderFactory senderFactory;
@Override @Override
public void onEnable() { public void onEnable() {
log = LogFactory.wrap(getLogger()); log = LogFactory.wrap(getLogger());
debugHandler = new DebugHandler(); debugHandler = new DebugHandler();
senderFactory = new BungeeSenderFactory(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
configuration = new BungeeConfig(this); configuration = new BungeeConfig(this);
@ -137,7 +138,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
// register commands // register commands
getLog().info("Registering commands..."); getLog().info("Registering commands...");
CommandManager commandManager = new CommandManager(this); CommandManager commandManager = new CommandManager(this);
getProxy().getPluginManager().registerCommand(this, new BungeeCommand(commandManager)); getProxy().getPluginManager().registerCommand(this, new BungeeCommand(this, commandManager));
// disable the default Bungee /perms command so it gets handled by the Bukkit plugin // disable the default Bungee /perms command so it gets handled by the Bukkit plugin
getProxy().getDisabledCommands().add("perms"); getProxy().getDisabledCommands().add("perms");
@ -229,16 +230,15 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getNotifyListeners() { public List<Sender> getSenders() {
return getProxy().getPlayers().stream() return getProxy().getPlayers().stream()
.map(p -> BungeeSenderFactory.get(this).wrap(p)) .map(p -> getSenderFactory().wrap(p))
.filter(Permission.LOG_NOTIFY::isAuthorized)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public Sender getConsoleSender() { public Sender getConsoleSender() {
return BungeeSenderFactory.get(this).wrap(getProxy().getConsole()); return getSenderFactory().wrap(getProxy().getConsole());
} }
@Override @Override

View File

@ -49,46 +49,142 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
/** /**
* Main internal interface for LuckPerms plugins, allowing the luckperms-common module to bind with the plugin instance. * Main internal interface for LuckPerms plugins, providing the base for abstraction throughout the project.
*
* All plugin platforms implement this interface. * All plugin platforms implement this interface.
*/ */
public interface LuckPermsPlugin { public interface LuckPermsPlugin {
/* /**
* Access to all of the main internal manager classes * Gets the user manager instance for the platform
* @return the user manager
*/ */
UserManager getUserManager(); UserManager getUserManager();
/**
* Gets the group manager instance for the platform
* @return the group manager
*/
GroupManager getGroupManager(); GroupManager getGroupManager();
/**
* Gets the track manager instance for the platform
* @return the track manager
*/
TrackManager getTrackManager(); TrackManager getTrackManager();
/**
* Gets the plugin's configuration
* @return the plugin config
*/
LPConfiguration getConfiguration(); LPConfiguration getConfiguration();
/**
* Gets the primary datastore instance. This is likely to be wrapped with extra layers for caching, etc.
* @return the datastore
*/
Datastore getDatastore(); Datastore getDatastore();
/**
* Gets the redis messaging instance if present. Could return null if redis is not enabled.
* @return the redis messaging service
*/
RedisMessaging getRedisMessaging(); RedisMessaging getRedisMessaging();
/**
* Gets a wrapped logger instance for the platform.
* @return the plugin's logger
*/
Logger getLog(); Logger getLog();
/**
* Gets the UUID caching store for the platform
* @return the uuid cache
*/
UuidCache getUuidCache(); UuidCache getUuidCache();
/**
* Returns the class implementing the LuckPermsAPI on this platform.
* @return the api
*/
ApiProvider getApiProvider(); ApiProvider getApiProvider();
/**
* Gets the importer instance
* @return the importer
*/
Importer getImporter(); Importer getImporter();
/**
* Gets the consecutive command executor instance
* @return the consecutive executor
*/
ConsecutiveExecutor getConsecutiveExecutor(); ConsecutiveExecutor getConsecutiveExecutor();
/**
* Gets the instance providing locale translations for the plugin
* @return the locale manager
*/
LocaleManager getLocaleManager(); LocaleManager getLocaleManager();
/**
* Gets the context manager.
* This object handles context accumulation for all players on the platform.
* @return the context manager
*/
ContextManager getContextManager(); ContextManager getContextManager();
/**
* Gets the class responsible for constructing PermissionCalculators on this platform.
* @return the permission calculator factory
*/
CalculatorFactory getCalculatorFactory(); CalculatorFactory getCalculatorFactory();
/**
* Gets the verbose debug handler instance.
* @return the debug handler instance
*/
DebugHandler getDebugHandler(); DebugHandler getDebugHandler();
/** /**
* Execute a runnable asynchronously
* @param r the task to run
*/
void doAsync(Runnable r);
/**
* Execute a runnable synchronously
* @param r the task to run
*/
void doSync(Runnable r);
/**
* Execute a runnable asynchronously on a loop
* @param r the task to run
* @param interval the time between runs in ticks
*/
void doAsyncRepeating(Runnable r, long interval);
/**
* Gets a string of the plugin's version
* @return the version of the plugin * @return the version of the plugin
*/ */
String getVersion(); String getVersion();
/** /**
* Gets the platform type this instance of LuckPerms is running on.
* @return the platform type * @return the platform type
*/ */
PlatformType getType(); PlatformType getType();
/** /**
* Gets the plugins main directory
* @return the main plugin directory * @return the main plugin directory
*/ */
File getMainDir(); File getMainDir();
/** /**
* Gets the plugins main data storage directory
* @return the platforms data folder * @return the platforms data folder
*/ */
File getDataFolder(); File getDataFolder();
@ -129,11 +225,13 @@ public interface LuckPermsPlugin {
boolean isOnline(UUID external); boolean isOnline(UUID external);
/** /**
* Gets a list of online Senders on the platform
* @return a {@link List} of senders online on the platform * @return a {@link List} of senders online on the platform
*/ */
List<Sender> getNotifyListeners(); List<Sender> getSenders();
/** /**
* Gets the console.
* @return the console sender of the instance * @return the console sender of the instance
*/ */
Sender getConsoleSender(); Sender getConsoleSender();
@ -147,7 +245,7 @@ public interface LuckPermsPlugin {
/** /**
* Gets a set of players ignoring logging output * Gets a set of players ignoring logging output
* @return a {@link Set} of uuids * @return a {@link Set} of {@link UUID}s
*/ */
Set<UUID> getIgnoringLogs(); Set<UUID> getIgnoringLogs();
@ -166,7 +264,7 @@ public interface LuckPermsPlugin {
Object getService(Class clazz); Object getService(Class clazz);
/** /**
* Used as a backup for migration * Gets the UUID of a player. Used as a backup for migration
* @param playerName the players name * @param playerName the players name
* @return a uuid if found, or null if not * @return a uuid if found, or null if not
*/ */
@ -180,27 +278,9 @@ public interface LuckPermsPlugin {
boolean isPluginLoaded(String name); boolean isPluginLoaded(String name);
/** /**
* Runs an update task * Gets the update task buffer of the platform, used for scheduling and running update tasks.
* @return the update task buffer instance
*/ */
BufferedRequest<Void> getUpdateTaskBuffer(); BufferedRequest<Void> getUpdateTaskBuffer();
/**
* Execute a runnable asynchronously
* @param r the task to run
*/
void doAsync(Runnable r);
/**
* Execute a runnable synchronously
* @param r the task to run
*/
void doSync(Runnable r);
/**
* Execute a runnable asynchronously on a loop
* @param r the task to run
* @param interval the time between runs in ticks
*/
void doAsyncRepeating(Runnable r, long interval);
} }

View File

@ -26,6 +26,7 @@ import me.lucko.luckperms.api.event.events.LogNotifyEvent;
import me.lucko.luckperms.common.LuckPermsPlugin; import me.lucko.luckperms.common.LuckPermsPlugin;
import me.lucko.luckperms.common.commands.Sender; import me.lucko.luckperms.common.commands.Sender;
import me.lucko.luckperms.common.constants.Message; import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.PermissionHolder; import me.lucko.luckperms.common.core.PermissionHolder;
import me.lucko.luckperms.common.groups.Group; import me.lucko.luckperms.common.groups.Group;
import me.lucko.luckperms.common.tracks.Track; import me.lucko.luckperms.common.tracks.Track;
@ -56,15 +57,17 @@ public class LogEntry extends me.lucko.luckperms.api.LogEntry {
final String msg = super.getFormatted(); final String msg = super.getFormatted();
List<Sender> senders = plugin.getNotifyListeners(); List<Sender> senders = plugin.getSenders();
senders.add(plugin.getConsoleSender()); senders.add(plugin.getConsoleSender());
if (sender == null) { if (sender == null) {
senders.stream() senders.stream()
.filter(Permission.LOG_NOTIFY::isAuthorized)
.filter(s -> !plugin.getIgnoringLogs().contains(s.getUuid())) .filter(s -> !plugin.getIgnoringLogs().contains(s.getUuid()))
.forEach(s -> Message.LOG.send(s, msg)); .forEach(s -> Message.LOG.send(s, msg));
} else { } else {
senders.stream() senders.stream()
.filter(Permission.LOG_NOTIFY::isAuthorized)
.filter(s -> !plugin.getIgnoringLogs().contains(s.getUuid())) .filter(s -> !plugin.getIgnoringLogs().contains(s.getUuid()))
.filter(s -> !s.getUuid().equals(sender.getUuid())) .filter(s -> !s.getUuid().equals(sender.getUuid()))
.forEach(s -> Message.LOG.send(s, msg)); .forEach(s -> Message.LOG.send(s, msg));

View File

@ -61,6 +61,9 @@ public class User extends PermissionHolder implements Identifiable<UserIdentifie
@Setter @Setter
private String primaryGroup = null; private String primaryGroup = null;
/**
* The users data cache instance, if present.
*/
@Getter @Getter
private UserCache userData = null; private UserCache userData = null;

View File

@ -26,6 +26,10 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
/**
* Basic Future implementation
* @param <R> the return type
*/
public class AbstractFuture<R> implements LPFuture<R> { public class AbstractFuture<R> implements LPFuture<R> {
private final CountDownLatch latch = new CountDownLatch(1); private final CountDownLatch latch = new CountDownLatch(1);
private R value; private R value;

View File

@ -32,6 +32,9 @@ import me.lucko.luckperms.common.users.User;
import java.util.UUID; import java.util.UUID;
/**
* An abstract listener shared by Bukkit & Sponge.
*/
@AllArgsConstructor @AllArgsConstructor
public class AbstractListener { public class AbstractListener {
private final LuckPermsPlugin plugin; private final LuckPermsPlugin plugin;

View File

@ -25,6 +25,9 @@ package me.lucko.luckperms.common.utils;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import me.lucko.luckperms.common.constants.Patterns; import me.lucko.luckperms.common.constants.Patterns;
/**
* Utility for checking arguments for consistency
*/
@UtilityClass @UtilityClass
public class ArgumentChecker { public class ArgumentChecker {

View File

@ -27,19 +27,24 @@ import lombok.*;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* Holds a buffer of objects to be processed after they've been in the buffer for a given time. * Thread-safe buffer utility. Holds a buffer of objects to be processed after they've been waiting in the buffer
* for a given time. If the same object is pushed to the buffer again in that time, its wait time is reset.
*
* @param <T> the type of objects in the buffer * @param <T> the type of objects in the buffer
* @param <R> the type of result produced by the final process * @param <R> the type of result produced by the final process
*/ */
public abstract class Buffer<T, R> implements Runnable { public abstract class Buffer<T, R> implements Runnable {
private static final long DEFAULT_FLUSH_TIME = 1000; // 1 second private static final long DEFAULT_FLUSH_TIME = 1000; // 1 second
private final ReentrantLock lock = new ReentrantLock();
private final List<BufferedObject<T, R>> buffer = new LinkedList<>(); private final List<BufferedObject<T, R>> buffer = new LinkedList<>();
public LPFuture<R> enqueue(@NonNull T t) { public LPFuture<R> enqueue(@NonNull T t) {
synchronized (buffer) { lock.lock();
try {
ListIterator<BufferedObject<T, R>> it = buffer.listIterator(); ListIterator<BufferedObject<T, R>> it = buffer.listIterator();
BufferedObject<T, R> o = null; BufferedObject<T, R> o = null;
@ -62,6 +67,8 @@ public abstract class Buffer<T, R> implements Runnable {
buffer.add(o); buffer.add(o);
return o.getFuture(); return o.getFuture();
} finally {
lock.unlock();
} }
} }
@ -70,7 +77,8 @@ public abstract class Buffer<T, R> implements Runnable {
public void flush(long flushTime) { public void flush(long flushTime) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
synchronized (buffer) { lock.lock();
try {
ListIterator<BufferedObject<T, R>> it = buffer.listIterator(buffer.size()); ListIterator<BufferedObject<T, R>> it = buffer.listIterator(buffer.size());
while (it.hasPrevious()) { while (it.hasPrevious()) {
@ -85,6 +93,8 @@ public abstract class Buffer<T, R> implements Runnable {
it.remove(); it.remove();
} }
} }
} finally {
lock.unlock();
} }
} }

View File

@ -30,14 +30,20 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
/**
* Thread-safe request buffer.
*
* Waits for the buffer time to pass before performing the operation. If the task is called again in that time, the
* buffer time is reset.
*
* @param <T> the return type
*/
@RequiredArgsConstructor @RequiredArgsConstructor
public abstract class BufferedRequest<T> { public abstract class BufferedRequest<T> {
private final long bufferTimeMillis; private final long bufferTimeMillis;
private final Consumer<Runnable> executor; private final Consumer<Runnable> executor;
private WeakReference<Processor<T>> processor = null; private WeakReference<Processor<T>> processor = null;
@Getter
private ReentrantLock lock = new ReentrantLock(); private ReentrantLock lock = new ReentrantLock();
public LPFuture<T> request() { public LPFuture<T> request() {
@ -66,7 +72,6 @@ public abstract class BufferedRequest<T> {
protected abstract T perform(); protected abstract T perform();
@RequiredArgsConstructor @RequiredArgsConstructor
private static class Processor<R> implements Runnable { private static class Processor<R> implements Runnable {
private final long delayMillis; private final long delayMillis;

View File

@ -1,23 +1,7 @@
/* /*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me> * All credit to Essentials / EssentialsX for this class
* * https://github.com/drtshock/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
* Permission is hereby granted, free of charge, to any person obtaining a copy * https://github.com/essentials/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/ */
package me.lucko.luckperms.common.utils; package me.lucko.luckperms.common.utils;
@ -30,9 +14,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* All credit to Essentials / EssentialsX for this class * Translates unix timestamps / durations into a readable format
* https://github.com/drtshock/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
* https://github.com/essentials/Essentials/blob/2.x/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
*/ */
@UtilityClass @UtilityClass
public class DateUtil { public class DateUtil {
@ -52,13 +34,7 @@ public class DateUtil {
*/ */
public static long parseDateDiff(String time, boolean future) throws IllegalDateException { public static long parseDateDiff(String time, boolean future) throws IllegalDateException {
Matcher m = TIME_PATTERN.matcher(time); Matcher m = TIME_PATTERN.matcher(time);
int years = 0; int years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
int months = 0;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
boolean found = false; boolean found = false;
while (m.find()) { while (m.find()) {
if (m.group() == null || m.group().isEmpty()) { if (m.group() == null || m.group().isEmpty()) {
@ -137,8 +113,7 @@ public class DateUtil {
int fromYear = fromDate.get(year); int fromYear = fromDate.get(year);
int toYear = toDate.get(year); int toYear = toDate.get(year);
if (Math.abs(fromYear - toYear) > MAX_YEARS) { if (Math.abs(fromYear - toYear) > MAX_YEARS) {
toDate.set(year, fromYear + toDate.set(year, fromYear + (future ? MAX_YEARS : -MAX_YEARS));
(future ? MAX_YEARS : -MAX_YEARS));
} }
int diff = 0; int diff = 0;

View File

@ -36,11 +36,11 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class DebugHandler { public class DebugHandler {
private final Map<Reciever, List<String>> listeners = new ConcurrentHashMap<>(); private final Map<Receiver, List<String>> listeners = new ConcurrentHashMap<>();
public void printOutput(String checked, String node, Tristate value) { public void printOutput(String checked, String node, Tristate value) {
all: all:
for (Map.Entry<Reciever, List<String>> e : listeners.entrySet()) { for (Map.Entry<Receiver, List<String>> e : listeners.entrySet()) {
for (String filter : e.getValue()) { for (String filter : e.getValue()) {
if (node.toLowerCase().startsWith(filter.toLowerCase())) { if (node.toLowerCase().startsWith(filter.toLowerCase())) {
continue; continue;
@ -58,17 +58,17 @@ public class DebugHandler {
} }
public void register(Sender sender, List<String> filters) { public void register(Sender sender, List<String> filters) {
listeners.put(new Reciever(sender.getUuid(), sender), ImmutableList.copyOf(filters)); listeners.put(new Receiver(sender.getUuid(), sender), ImmutableList.copyOf(filters));
} }
public void unregister(UUID uuid) { public void unregister(UUID uuid) {
listeners.remove(new Reciever(uuid, null)); listeners.remove(new Receiver(uuid, null));
} }
@Getter @Getter
@EqualsAndHashCode(of = "uuid") @EqualsAndHashCode(of = "uuid")
@AllArgsConstructor @AllArgsConstructor
private static final class Reciever { private static final class Receiver {
private final UUID uuid; private final UUID uuid;
private final Sender sender; private final Sender sender;
} }

View File

@ -27,7 +27,7 @@ import lombok.experimental.Delegate;
import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.Node;
/** /**
* Holds a Node and where it was inherited from * Holds a Node and where it was inherited from. All calls are passed onto the contained Node instance.
*/ */
@Getter @Getter
@ToString @ToString

View File

@ -25,6 +25,9 @@ package me.lucko.luckperms.common.utils;
import lombok.experimental.UtilityClass; import lombok.experimental.UtilityClass;
import me.lucko.luckperms.api.Logger; import me.lucko.luckperms.api.Logger;
/**
* Utility to help create wrapped log instances
*/
@UtilityClass @UtilityClass
public class LogFactory { public class LogFactory {
public static Logger wrap(org.slf4j.Logger l) { public static Logger wrap(org.slf4j.Logger l) {

View File

@ -29,6 +29,9 @@ import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/**
* A collection of predicate utilities used mostly in command classes
*/
@SuppressWarnings({"WeakerAccess", "unused"}) @SuppressWarnings({"WeakerAccess", "unused"})
@UtilityClass @UtilityClass
public class Predicates { public class Predicates {

View File

@ -123,11 +123,13 @@ public class LPSpongePlugin implements LuckPermsPlugin {
private CalculatorFactory calculatorFactory; private CalculatorFactory calculatorFactory;
private BufferedRequest<Void> updateTaskBuffer; private BufferedRequest<Void> updateTaskBuffer;
private DebugHandler debugHandler; private DebugHandler debugHandler;
private SpongeSenderFactory senderFactory;
@Listener @Listener
public void onEnable(GamePreInitializationEvent event) { public void onEnable(GamePreInitializationEvent event) {
log = LogFactory.wrap(logger); log = LogFactory.wrap(logger);
debugHandler = new DebugHandler(); debugHandler = new DebugHandler();
senderFactory = new SpongeSenderFactory(this);
timings = new LPTimings(this); timings = new LPTimings(this);
getLog().info("Loading configuration..."); getLog().info("Loading configuration...");
@ -304,16 +306,15 @@ public class LPSpongePlugin implements LuckPermsPlugin {
} }
@Override @Override
public List<Sender> getNotifyListeners() { public List<Sender> getSenders() {
return game.getServer().getOnlinePlayers().stream() return game.getServer().getOnlinePlayers().stream()
.map(s -> SpongeSenderFactory.get(this).wrap(s)) .map(s -> getSenderFactory().wrap(s))
.filter(Permission.LOG_NOTIFY::isAuthorized)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public Sender getConsoleSender() { public Sender getConsoleSender() {
return SpongeSenderFactory.get(this).wrap(game.getServer().getConsole()); return getSenderFactory().wrap(game.getServer().getConsole());
} }
@Override @Override

View File

@ -54,7 +54,7 @@ class SpongeCommand extends CommandManager implements CommandCallable {
public CommandResult process(CommandSource source, String s) throws CommandException { public CommandResult process(CommandSource source, String s) throws CommandException {
try (Timing ignored = plugin.getTimings().time(LPTiming.ON_COMMAND)) { try (Timing ignored = plugin.getTimings().time(LPTiming.ON_COMMAND)) {
onCommand( onCommand(
SpongeSenderFactory.get(getPlugin()).wrap(source), plugin.getSenderFactory().wrap(source),
"perms", "perms",
Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(s)), Util.stripQuotes(Splitter.on(Patterns.COMMAND_SEPARATOR).omitEmptyStrings().splitToList(s)),
Callback.empty() Callback.empty()
@ -66,13 +66,13 @@ class SpongeCommand extends CommandManager implements CommandCallable {
@Override @Override
public List<String> getSuggestions(CommandSource source, String s, @Nullable Location<World> location) throws CommandException { public List<String> getSuggestions(CommandSource source, String s, @Nullable Location<World> location) throws CommandException {
try (Timing ignored = plugin.getTimings().time(LPTiming.COMMAND_TAB_COMPLETE)) { try (Timing ignored = plugin.getTimings().time(LPTiming.COMMAND_TAB_COMPLETE)) {
return onTabComplete(SpongeSenderFactory.get(getPlugin()).wrap(source), Splitter.on(' ').splitToList(s)); return onTabComplete(plugin.getSenderFactory().wrap(source), Splitter.on(' ').splitToList(s));
} }
} }
public List<String> getSuggestions(CommandSource source, String s) throws CommandException { public List<String> getSuggestions(CommandSource source, String s) throws CommandException {
try (Timing ignored = plugin.getTimings().time(LPTiming.COMMAND_TAB_COMPLETE)) { try (Timing ignored = plugin.getTimings().time(LPTiming.COMMAND_TAB_COMPLETE)) {
return onTabComplete(SpongeSenderFactory.get(getPlugin()).wrap(source), Splitter.on(' ').splitToList(s)); return onTabComplete(plugin.getSenderFactory().wrap(source), Splitter.on(' ').splitToList(s));
} }
} }

View File

@ -32,19 +32,10 @@ import org.spongepowered.api.text.serializer.TextSerializers;
import java.util.UUID; import java.util.UUID;
public class SpongeSenderFactory extends SenderFactory<CommandSource> { public class SpongeSenderFactory extends SenderFactory<CommandSource> {
private static SpongeSenderFactory instance = null; public SpongeSenderFactory(LuckPermsPlugin plugin) {
private SpongeSenderFactory(LuckPermsPlugin plugin) {
super(plugin); super(plugin);
} }
public static synchronized SpongeSenderFactory get(LuckPermsPlugin plugin) {
if (instance == null) {
instance = new SpongeSenderFactory(plugin);
}
return instance;
}
@Override @Override
protected String getName(CommandSource source) { protected String getName(CommandSource source) {
if (source instanceof Player) { if (source instanceof Player) {

View File

@ -22,6 +22,7 @@
package me.lucko.luckperms.sponge.service; package me.lucko.luckperms.sponge.service;
import com.google.common.collect.ImmutableSet;
import lombok.NonNull; import lombok.NonNull;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import org.spongepowered.api.service.context.Context; import org.spongepowered.api.service.context.Context;
@ -97,7 +98,7 @@ public abstract class LuckPermsSubject implements Subject {
@Override @Override
@Deprecated @Deprecated
public Set<Context> getActiveContexts() { public Set<Context> getActiveContexts() {
return LuckPermsService.convertContexts(getActiveContextSet()); return ImmutableSet.copyOf(LuckPermsService.convertContexts(getActiveContextSet()));
} }
} }

View File

@ -28,6 +28,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull;
import me.lucko.luckperms.api.Node; import me.lucko.luckperms.api.Node;
import me.lucko.luckperms.api.context.ContextSet; import me.lucko.luckperms.api.context.ContextSet;
import me.lucko.luckperms.common.core.NodeBuilder; import me.lucko.luckperms.common.core.NodeBuilder;
@ -97,12 +98,12 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public Map<String, Boolean> getPermissions(Set<Context> contexts) { public Map<String, Boolean> getPermissions(@NonNull Set<Context> contexts) {
return getAllPermissions().getOrDefault(contexts, ImmutableMap.of()); return getAllPermissions().getOrDefault(contexts, ImmutableMap.of());
} }
@Override @Override
public boolean setPermission(Set<Context> contexts, String permission, Tristate tristate) { public boolean setPermission(@NonNull Set<Context> contexts, @NonNull String permission, @NonNull Tristate tristate) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_PERMISSION)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_PERMISSION)) {
if (tristate == Tristate.UNDEFINED) { if (tristate == Tristate.UNDEFINED) {
// Unset // Unset
@ -158,7 +159,7 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public boolean clearPermissions(Set<Context> c) { public boolean clearPermissions(@NonNull Set<Context> c) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_PERMISSIONS)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_PERMISSIONS)) {
List<Node> toRemove = new ArrayList<>(); List<Node> toRemove = new ArrayList<>();
for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) { for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) {
@ -232,12 +233,12 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public List<Subject> getParents(Set<Context> contexts) { public List<Subject> getParents(@NonNull Set<Context> contexts) {
return getAllParents().getOrDefault(contexts, ImmutableList.of()); return getAllParents().getOrDefault(contexts, ImmutableList.of());
} }
@Override @Override
public boolean addParent(Set<Context> set, Subject subject) { public boolean addParent(@NonNull Set<Context> set, @NonNull Subject subject) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_ADD_PARENT)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_ADD_PARENT)) {
if (subject instanceof LuckPermsGroupSubject) { if (subject instanceof LuckPermsGroupSubject) {
LuckPermsGroupSubject permsSubject = ((LuckPermsGroupSubject) subject); LuckPermsGroupSubject permsSubject = ((LuckPermsGroupSubject) subject);
@ -263,7 +264,7 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public boolean removeParent(Set<Context> set, Subject subject) { public boolean removeParent(@NonNull Set<Context> set, @NonNull Subject subject) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_REMOVE_PARENT)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_REMOVE_PARENT)) {
if (subject instanceof LuckPermsGroupSubject) { if (subject instanceof LuckPermsGroupSubject) {
LuckPermsGroupSubject permsSubject = ((LuckPermsGroupSubject) subject); LuckPermsGroupSubject permsSubject = ((LuckPermsGroupSubject) subject);
@ -315,7 +316,7 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public boolean clearParents(Set<Context> set) { public boolean clearParents(@NonNull Set<Context> set) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_PARENTS)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_PARENTS)) {
List<Node> toRemove = new ArrayList<>(); List<Node> toRemove = new ArrayList<>();
for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) { for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) {
@ -421,12 +422,12 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public Map<String, String> getOptions(Set<Context> set) { public Map<String, String> getOptions(@NonNull Set<Context> set) {
return getAllOptions().getOrDefault(set, ImmutableMap.of()); return getAllOptions().getOrDefault(set, ImmutableMap.of());
} }
@Override @Override
public boolean setOption(Set<Context> set, String key, String value) { public boolean setOption(@NonNull Set<Context> set, @NonNull String key, @NonNull String value) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_OPTION)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_SET_OPTION)) {
ContextSet context = LuckPermsService.convertContexts(set); ContextSet context = LuckPermsService.convertContexts(set);
@ -452,7 +453,7 @@ public class LuckPermsSubjectData implements SubjectData {
} }
@Override @Override
public boolean clearOptions(Set<Context> set) { public boolean clearOptions(@NonNull Set<Context> set) {
try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_OPTIONS)) { try (Timing i = service.getPlugin().getTimings().time(LPTiming.LP_SUBJECT_CLEAR_OPTIONS)) {
List<Node> toRemove = new ArrayList<>(); List<Node> toRemove = new ArrayList<>();
for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) { for (Node n : enduring ? holder.getNodes() : holder.getTransientNodes()) {

View File

@ -40,7 +40,6 @@ import org.spongepowered.api.util.Tristate;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
public class GroupCollection implements SubjectCollection { public class GroupCollection implements SubjectCollection {
private final LuckPermsService service; private final LuckPermsService service;
@ -92,7 +91,7 @@ public class GroupCollection implements SubjectCollection {
return manager.getAll().values().stream() return manager.getAll().values().stream()
.map(u -> LuckPermsGroupSubject.wrapGroup(u, service)) .map(u -> LuckPermsGroupSubject.wrapGroup(u, service))
.filter(sub -> sub.getPermissionValue(cs, node) != Tristate.UNDEFINED) .filter(sub -> sub.getPermissionValue(cs, node) != Tristate.UNDEFINED)
.collect(Collectors.toMap(sub -> sub, sub -> sub.getPermissionValue(cs, node).asBoolean())); .collect(ImmutableCollectors.toImmutableMap(sub -> sub, sub -> sub.getPermissionValue(cs, node).asBoolean()));
} }
@Override @Override

View File

@ -62,13 +62,6 @@ public class UserCollection implements SubjectCollection {
private final SimpleCollection fallback; private final SimpleCollection fallback;
private final LoadingCache<UUID, LuckPermsUserSubject> users = CacheBuilder.newBuilder() private final LoadingCache<UUID, LuckPermsUserSubject> users = CacheBuilder.newBuilder()
/*
.removalListener((RemovalListener<UUID, LuckPermsUserSubject>) r -> {
if (r.getValue() != null) {
r.getValue().deprovision();
}
})
*/
.build(new CacheLoader<UUID, LuckPermsUserSubject>() { .build(new CacheLoader<UUID, LuckPermsUserSubject>() {
@Override @Override
public LuckPermsUserSubject load(UUID uuid) throws Exception { public LuckPermsUserSubject load(UUID uuid) throws Exception {

View File

@ -26,6 +26,7 @@ import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -36,7 +37,6 @@ import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection; import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.util.Tristate; import org.spongepowered.api.util.Tristate;
import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -83,7 +83,7 @@ public class PersistedCollection implements SubjectCollection {
@Override @Override
public Map<Subject, Boolean> getAllWithPermission(@NonNull String id) { public Map<Subject, Boolean> getAllWithPermission(@NonNull String id) {
return getAllWithPermission(Collections.emptySet(), id); return getAllWithPermission(ImmutableSet.of(), id);
} }
@Override @Override

View File

@ -24,6 +24,7 @@ package me.lucko.luckperms.sponge.service.persisted;
import co.aikar.timings.Timing; import co.aikar.timings.Timing;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import me.lucko.luckperms.common.utils.BufferedRequest; import me.lucko.luckperms.common.utils.BufferedRequest;
@ -196,7 +197,7 @@ public class PersistedSubject implements Subject {
@Override @Override
public Set<Context> getActiveContexts() { public Set<Context> getActiveContexts() {
try (Timing ignored = service.getPlugin().getTimings().time(LPTiming.PERSISTED_SUBJECT_GET_ACTIVE_CONTEXTS)) { try (Timing ignored = service.getPlugin().getTimings().time(LPTiming.PERSISTED_SUBJECT_GET_ACTIVE_CONTEXTS)) {
return LuckPermsService.convertContexts(service.getPlugin().getContextManager().getApplicableContext(this)); return ImmutableSet.copyOf(LuckPermsService.convertContexts(service.getPlugin().getContextManager().getApplicableContext(this)));
} }
} }
} }

View File

@ -25,20 +25,20 @@ package me.lucko.luckperms.sponge.service.simple;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.common.utils.ImmutableCollectors;
import me.lucko.luckperms.sponge.service.LuckPermsService; import me.lucko.luckperms.sponge.service.LuckPermsService;
import org.spongepowered.api.service.context.Context; import org.spongepowered.api.service.context.Context;
import org.spongepowered.api.service.permission.Subject; import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection; import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.util.Tristate; import org.spongepowered.api.util.Tristate;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
/** /**
* Super simple SubjectCollection implementation * Super simple SubjectCollection implementation
@ -70,17 +70,17 @@ public class SimpleCollection implements SubjectCollection {
@Override @Override
public Iterable<Subject> getAllSubjects() { public Iterable<Subject> getAllSubjects() {
return subjects.asMap().values().stream().map(s -> (Subject) s).collect(Collectors.toList()); return subjects.asMap().values().stream().map(s -> (Subject) s).collect(ImmutableCollectors.toImmutableList());
} }
@Override @Override
public Map<Subject, Boolean> getAllWithPermission(@NonNull String id) { public Map<Subject, Boolean> getAllWithPermission(@NonNull String id) {
return getAllWithPermission(Collections.emptySet(), id); return getAllWithPermission(ImmutableSet.of(), id);
} }
@Override @Override
public Map<Subject, Boolean> getAllWithPermission(@NonNull Set<Context> contexts, @NonNull String node) { public Map<Subject, Boolean> getAllWithPermission(@NonNull Set<Context> contexts, @NonNull String node) {
Map<Subject, Boolean> m = new HashMap<>(); ImmutableMap.Builder<Subject, Boolean> m = ImmutableMap.builder();
for (Subject subject : subjects.asMap().values()) { for (Subject subject : subjects.asMap().values()) {
Tristate ts = subject.getPermissionValue(contexts, node); Tristate ts = subject.getPermissionValue(contexts, node);
if (ts != Tristate.UNDEFINED) { if (ts != Tristate.UNDEFINED) {
@ -88,7 +88,7 @@ public class SimpleCollection implements SubjectCollection {
} }
} }
return m; return m.build();
} }
@Override @Override

View File

@ -24,6 +24,7 @@ package me.lucko.luckperms.sponge.service.simple;
import co.aikar.timings.Timing; import co.aikar.timings.Timing;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
import me.lucko.luckperms.sponge.service.LuckPermsService; import me.lucko.luckperms.sponge.service.LuckPermsService;
@ -162,7 +163,7 @@ public class SimpleSubject implements Subject {
@Override @Override
public Set<Context> getActiveContexts() { public Set<Context> getActiveContexts() {
try (Timing ignored = service.getPlugin().getTimings().time(LPTiming.SIMPLE_SUBJECT_GET_ACTIVE_CONTEXTS)) { try (Timing ignored = service.getPlugin().getTimings().time(LPTiming.SIMPLE_SUBJECT_GET_ACTIVE_CONTEXTS)) {
return LuckPermsService.convertContexts(service.getPlugin().getContextManager().getApplicableContext(this)); return ImmutableSet.copyOf(LuckPermsService.convertContexts(service.getPlugin().getContextManager().getApplicableContext(this)));
} }
} }
} }