net.luckperms.api.context.ContextSet Java Examples

The following examples show how to use net.luckperms.api.context.ContextSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LuckPermsHook.java    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    ImmutableContextSet.Builder builder = ImmutableContextSet.builder();

    builder.add(CONTEXT_LINKED, "true");
    builder.add(CONTEXT_LINKED, "false");

    builder.add(CONTEXT_BOOSTING, "true");
    builder.add(CONTEXT_BOOSTING, "false");

    Guild mainGuild = DiscordSRV.getPlugin().getMainGuild();
    if (mainGuild != null) {
        for (Role role : mainGuild.getRoles()) {
            builder.add(CONTEXT_ROLE, role.getName());
        }
    }

    return builder.build();
}
 
Example #2
Source File: MutableContextSetImpl.java    From LuckPerms with MIT License 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof ContextSet)) return false;
    final ContextSet that = (ContextSet) o;

    final Multimap<String, String> thatBacking;
    if (that instanceof AbstractContextSet) {
        thatBacking = ((AbstractContextSet) that).backing();
    } else {
        Map<String, Set<String>> thatMap = that.toMap();
        ImmutableSetMultimap.Builder<String, String> thatBuilder = ImmutableSetMultimap.builder();
        for (Map.Entry<String, Set<String>> e : thatMap.entrySet()) {
            thatBuilder.putAll(e.getKey(), e.getValue());
        }
        thatBacking = thatBuilder.build();
    }

    return backing().equals(thatBacking);
}
 
Example #3
Source File: ImmutableContextSetImpl.java    From LuckPerms with MIT License 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof ContextSet)) return false;
    final ContextSet that = (ContextSet) o;

    // fast(er) path for ImmutableContextSet comparisons
    if (that instanceof ImmutableContextSetImpl) {
        ImmutableContextSetImpl immutableThat = (ImmutableContextSetImpl) that;
        if (this.hashCode != immutableThat.hashCode) return false;
    }

    final Multimap<String, String> thatBacking;
    if (that instanceof AbstractContextSet) {
        thatBacking = ((AbstractContextSet) that).backing();
    } else {
        Map<String, Set<String>> thatMap = that.toMap();
        ImmutableSetMultimap.Builder<String, String> thatBuilder = ImmutableSetMultimap.builder();
        for (Map.Entry<String, Set<String>> e : thatMap.entrySet()) {
            thatBuilder.putAll(e.getKey(), e.getValue());
        }
        thatBacking = thatBuilder.build();
    }

    return backing().equals(thatBacking);
}
 
Example #4
Source File: ContextSetConfigurateSerializer.java    From LuckPerms with MIT License 6 votes vote down vote up
public static ConfigurationNode serializeContextSet(ContextSet contextSet) {
    ConfigurationNode data = SimpleConfigurationNode.root();
    Map<String, Set<String>> map = contextSet.toMap();

    for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
        List<String> values = new ArrayList<>(entry.getValue());
        int size = values.size();

        if (size == 1) {
            data.getNode(entry.getKey()).setValue(values.get(0));
        } else if (size > 1) {
            data.getNode(entry.getKey()).setValue(values);
        }
    }

    return data;
}
 
Example #5
Source File: ContextSetConfigurateSerializer.java    From LuckPerms with MIT License 6 votes vote down vote up
public static ContextSet deserializeContextSet(ConfigurationNode data) {
    Preconditions.checkArgument(data.hasMapChildren());
    Map<Object, ? extends ConfigurationNode> dataMap = data.getChildrenMap();

    if (dataMap.isEmpty()) {
        return ImmutableContextSetImpl.EMPTY;
    }

    MutableContextSet map = new MutableContextSetImpl();
    for (Map.Entry<Object, ? extends ConfigurationNode> e : dataMap.entrySet()) {
        String k = e.getKey().toString();
        ConfigurationNode v = e.getValue();

        if (v.hasListChildren()) {
            List<? extends ConfigurationNode> values = v.getChildrenList();
            for (ConfigurationNode value : values) {
                map.add(k, value.getString());
            }
        } else {
            map.add(k, v.getString());
        }
    }

    return map;
}
 
Example #6
Source File: ContextSetJsonSerializer.java    From LuckPerms with MIT License 6 votes vote down vote up
public static JsonObject serializeContextSet(ContextSet contextSet) {
    JsonObject data = new JsonObject();
    Map<String, Set<String>> map = contextSet.toMap();

    for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
        List<String> values = new ArrayList<>(entry.getValue());
        int size = values.size();

        if (size == 1) {
            data.addProperty(entry.getKey(), values.get(0));
        } else if (size > 1) {
            JsonArray arr = new JsonArray();
            for (String s : values) {
                arr.add(new JsonPrimitive(s));
            }
            data.add(entry.getKey(), arr);
        }
    }

    return data;
}
 
Example #7
Source File: ContextSetJsonSerializer.java    From LuckPerms with MIT License 6 votes vote down vote up
public static ContextSet deserializeContextSet(JsonElement element) {
    Preconditions.checkArgument(element.isJsonObject());
    JsonObject data = element.getAsJsonObject();

    if (data.entrySet().isEmpty()) {
        return ImmutableContextSetImpl.EMPTY;
    }

    MutableContextSet map = new MutableContextSetImpl();
    for (Map.Entry<String, JsonElement> e : data.entrySet()) {
        String k = e.getKey();
        JsonElement v = e.getValue();
        if (v.isJsonArray()) {
            JsonArray values = v.getAsJsonArray();
            for (JsonElement value : values) {
                map.add(k, value.getAsString());
            }
        } else {
            map.add(k, v.getAsString());
        }
    }

    return map;
}
 
Example #8
Source File: LuckPermsProvider.java    From GriefDefender with MIT License 6 votes vote down vote up
public Tristate getPermissionValue(GDPermissionHolder holder, String permission, ContextSet contexts, PermissionDataType type) {
    final PermissionHolder permissionHolder = this.getLuckPermsHolder(holder);
    if (permissionHolder == null) {
        return Tristate.UNDEFINED;
    }

    QueryOptions query = null;
    if (type == PermissionDataType.TRANSIENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, DEFAULT_TRANSIENT_ONLY).context(contexts).build();
    } else if (type == PermissionDataType.PERSISTENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, DEFAULT_PERSISTENT_ONLY).context(contexts).build();
    } else if (type == PermissionDataType.USER_PERSISTENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, USER_PERSISTENT_ONLY).context(contexts).build();
    } else {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).context(contexts).build();
    }
    CachedPermissionData cachedData = permissionHolder.getCachedData().getPermissionData(query);
    return getGDTristate(cachedData.checkPermission(permission));
}
 
Example #9
Source File: PermissionHolder.java    From LuckPerms with MIT License 6 votes vote down vote up
public boolean removeIf(DataType dataType, @Nullable ContextSet contextSet, Predicate<? super Node> predicate, boolean giveDefault) {
    NodeMap data = getData(dataType);
    ImmutableCollection<? extends Node> before = data.immutable().values();

    if (contextSet == null) {
        if (!data.removeIf(predicate)) {
            return false;
        }
    } else {
        if (!data.removeIf(contextSet, predicate)) {
            return false;
        }
    }

    if (getType() == HolderType.USER && giveDefault) {
        getPlugin().getUserManager().giveDefaultIfNeeded((User) this, false);
    }

    invalidateCache();

    ImmutableCollection<? extends Node> after = data.immutable().values();
    this.plugin.getEventDispatcher().dispatchNodeClear(this, dataType, before, after);

    return true;
}
 
Example #10
Source File: PermissionHolder.java    From LuckPerms with MIT License 6 votes vote down vote up
public boolean clearNodes(DataType dataType, ContextSet contextSet, boolean giveDefault) {
    NodeMap data = getData(dataType);
    ImmutableCollection<? extends Node> before = data.immutable().values();

    if (contextSet == null) {
        data.clear();
    } else {
        data.clear(contextSet);
    }

    if (getType() == HolderType.USER && giveDefault) {
        getPlugin().getUserManager().giveDefaultIfNeeded((User) this, false);
    }

    invalidateCache();

    ImmutableCollection<? extends Node> after = data.immutable().values();

    if (before.size() == after.size()) {
        return false;
    }

    this.plugin.getEventDispatcher().dispatchNodeClear(this, dataType, before, after);
    return true;
}
 
Example #11
Source File: NodeMap.java    From LuckPerms with MIT License 6 votes vote down vote up
boolean removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
    ImmutableContextSet context = contextSet.immutableCopy();

    boolean success = false;

    SortedSet<Node> nodesInContext = this.map.get(context);
    if (nodesInContext != null) {
        success = nodesInContext.removeIf(predicate);
    }

    SortedSet<InheritanceNode> inheritanceNodesInContext = this.inheritanceMap.get(context);
    if (inheritanceNodesInContext != null) {
        inheritanceNodesInContext.removeIf(predicate);
    }

    return success;
}
 
Example #12
Source File: LuckPermsProvider.java    From GriefDefender with MIT License 6 votes vote down vote up
public Tristate getPermissionValue(GDPermissionHolder holder, String permission, ContextSet contexts, PermissionDataType type) {
    final PermissionHolder permissionHolder = this.getLuckPermsHolder(holder);
    if (permissionHolder == null) {
        return Tristate.UNDEFINED;
    }

    QueryOptions query = null;
    if (type == PermissionDataType.TRANSIENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, DEFAULT_TRANSIENT_ONLY).context(contexts).build();
    } else if (type == PermissionDataType.PERSISTENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, DEFAULT_PERSISTENT_ONLY).context(contexts).build();
    } else if (type == PermissionDataType.USER_PERSISTENT) {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).option(DataTypeFilterFunction.KEY, USER_PERSISTENT_ONLY).context(contexts).build();
    } else {
        query = QueryOptions.builder(QueryMode.CONTEXTUAL).option(DataQueryOrderFunction.KEY, DEFAULT_DATA_QUERY_ORDER).context(contexts).build();
    }
    CachedPermissionData cachedData = permissionHolder.getCachedData().getPermissionData(query);
    return getGDTristate(cachedData.checkPermission(permission));
}
 
Example #13
Source File: ArgumentPermissions.java    From LuckPerms with MIT License 6 votes vote down vote up
/**
 * Checks if the sender has permission to act using a given group
 *
 * @param plugin the plugin instance
 * @param sender the sender to check
 * @param targetGroupName the target group
 * @param contextSet the contexts the sender is trying to act within
 * @return true if the sender should NOT be allowed to act, true if they should
 */
public static boolean checkGroup(LuckPermsPlugin plugin, Sender sender, String targetGroupName, ContextSet contextSet) {
    if (!plugin.getConfiguration().get(ConfigKeys.REQUIRE_SENDER_GROUP_MEMBERSHIP_TO_MODIFY)) {
        return false;
    }

    if (sender.isConsole()) {
        return false;
    }

    User user = plugin.getUserManager().getIfLoaded(sender.getUniqueId());
    if (user == null) {
        throw new IllegalStateException("Unable to get a User for " + sender.getUniqueId() + " - " + sender.getName());
    }

    PermissionCache permissionData = user.getCachedData().getPermissionData(QueryOptionsImpl.DEFAULT_CONTEXTUAL.toBuilder().context(contextSet).build());
    TristateResult result = permissionData.checkPermission(Inheritance.key(targetGroupName), PermissionCheckEvent.Origin.INTERNAL);
    return result.result() != Tristate.TRUE || result.processorClass() != MapProcessor.class;
}
 
Example #14
Source File: SpongeUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public static Set<Context> getSpongeContexts(ContextSet contexts) {
    final Set<Context> spongeContexts = new HashSet<>();
    for (net.luckperms.api.context.Context mapEntry : contexts) {
        spongeContexts.add(new Context(mapEntry.getKey(), mapEntry.getValue()));
    }

    return spongeContexts;
}
 
Example #15
Source File: LuckPermsProvider.java    From GriefDefender with MIT License 5 votes vote down vote up
private void clearMeta(PermissionHolder holder, String metaKey, ContextSet set) {
    if (set.size() == 1 && set.containsKey("server")) {
        if (set.getAnyValue("server").get().equalsIgnoreCase("global")) {
            // LP does not remove meta if passing only global context so we need to make sure to pass none
            holder.data().clear(NodeType.META.predicate(node -> node.getMetaKey().equals(metaKey)));
            return;
        }
    }
    holder.data().clear(set, NodeType.META.predicate(node -> node.getMetaKey().equals(metaKey)));
}
 
Example #16
Source File: CompatibilityUtil.java    From LuckPerms with MIT License 5 votes vote down vote up
public static Set<Context> convertContexts(ContextSet contexts) {
    Objects.requireNonNull(contexts, "contexts");

    if (contexts.isEmpty()) {
        return EMPTY;
    }

    return new ForwardingImmutableContextSet(contexts.immutableCopy());
}
 
Example #17
Source File: WorldCalculator.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    Game game = this.plugin.getBootstrap().getGame();
    if (!game.isServerAvailable()) {
        return ImmutableContextSetImpl.EMPTY;
    }

    Collection<World> worlds = game.getServer().getWorlds();
    ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
    for (World world : worlds) {
        builder.add(DefaultContextKeys.WORLD_KEY, world.getName().toLowerCase());
    }
    return builder.build();
}
 
Example #18
Source File: LuckPermsProvider.java    From GriefDefender with MIT License 5 votes vote down vote up
public Map<Set<Context>, Map<String, Boolean>> getAllPermissions(GDPermissionHolder holder) {
    final PermissionHolder permissionHolder = this.getLuckPermsHolder(holder);
    if (permissionHolder == null) {
        return new HashMap<>();
    }

    final Collection<Node> nodes = permissionHolder.getNodes();
    Map<Set<Context>, Map<String, Boolean>> permissionMap = new HashMap<>();
    Map<ContextSet, Set<Context>> contextMap = new HashMap<>();
    for (Node node : nodes) {
        Set<Context> contexts = null;
        if (contextMap.get(node.getContexts()) == null) {
            contexts = getGPContexts(node.getContexts());
            contextMap.put(node.getContexts(), contexts);
        } else {
            contexts = contextMap.get(node.getContexts());
        }
        Map<String, Boolean> permissionEntry = permissionMap.get(contexts);
        if (permissionEntry == null) {
            permissionEntry = new HashMap<>();
            permissionEntry.put(node.getKey(), node.getValue());
            permissionMap.put(contexts, permissionEntry);
        } else {
            permissionEntry.put(node.getKey(), node.getValue());
        }
    }
    return permissionMap;
}
 
Example #19
Source File: BackendServerCalculator.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    Collection<RegisteredServer> servers = this.plugin.getBootstrap().getProxy().getAllServers();
    ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
    for (RegisteredServer server : servers) {
        builder.add(DefaultContextKeys.WORLD_KEY, server.getServerInfo().getName().toLowerCase());
    }
    return builder.build();
}
 
Example #20
Source File: QueryOptionsImpl.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public boolean satisfies(@NonNull ContextSet contextSet, @NonNull ContextSatisfyMode defaultContextSatisfyMode) {
    switch (this.mode) {
        case CONTEXTUAL:
            return contextSet.isSatisfiedBy(this.context, this.contextSatisfyMode == null ? defaultContextSatisfyMode : this.contextSatisfyMode);
        case NON_CONTEXTUAL:
            return true;
        default:
            throw new AssertionError();
    }
}
 
Example #21
Source File: ApiPermissionHolder.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void clear(@NonNull ContextSet contextSet) {
    Objects.requireNonNull(contextSet, "contextSet");
    if (ApiPermissionHolder.this.handle.clearNodes(this.dataType, contextSet, true)) {
        onNodeChange();
    }
}
 
Example #22
Source File: ApiPermissionHolder.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void clear(@NonNull ContextSet contextSet, @NonNull Predicate<? super Node> test) {
    Objects.requireNonNull(contextSet, "contextSet");
    Objects.requireNonNull(test, "test");
    if (ApiPermissionHolder.this.handle.removeIf(this.dataType, contextSet, test, true)) {
        onNodeChange();
    }
}
 
Example #23
Source File: AbstractContextSet.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public boolean isSatisfiedBy(@NonNull ContextSet other, @NonNull ContextSatisfyMode mode) {
    if (this == other) {
        return true;
    }

    Objects.requireNonNull(other, "other");
    Objects.requireNonNull(mode, "mode");

    // this is empty, it is always satisfied.
    if (this.isEmpty()) {
        return true;
    }

    // if this set isn't empty, but the other one is, then it can't be satisfied by it.
    if (other.isEmpty()) {
        return false;
    }

    // if mode is ALL_VALUES & this set has more entries than the other one, then it can't be satisfied by it.
    if (mode == ContextSatisfyMode.ALL_VALUES_PER_KEY && this.size() > other.size()) {
        return false;
    }

    // return true if 'other' contains all of 'this', according to the mode.
    return otherContainsAll(other, mode);
}
 
Example #24
Source File: MutableContextSetImpl.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void addAll(@NonNull ContextSet contextSet) {
    Objects.requireNonNull(contextSet, "contextSet");
    if (contextSet instanceof AbstractContextSet) {
        AbstractContextSet other = ((AbstractContextSet) contextSet);
        other.copyTo(this.map);
    } else {
        addAll(contextSet.toSet());
    }
}
 
Example #25
Source File: WorldCalculator.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ContextSet estimatePotentialContexts() {
    Collection<Level> worlds = this.plugin.getBootstrap().getServer().getLevels().values();
    ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
    for (Level world : worlds) {
        builder.add(DefaultContextKeys.WORLD_KEY, world.getName().toLowerCase());
    }
    return builder.build();
}
 
Example #26
Source File: ImmutableContextSetImpl.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public @NonNull BuilderImpl addAll(@NonNull ContextSet contextSet) {
    Objects.requireNonNull(contextSet, "contextSet");
    if (contextSet instanceof AbstractContextSet) {
        AbstractContextSet other = ((AbstractContextSet) contextSet);
        if (!other.isEmpty()) {
            builder().putAll(other.backing());
        }
    } else {
        addAll(contextSet.toSet());
    }
    return this;
}
 
Example #27
Source File: MessageUtils.java    From LuckPerms with MIT License 5 votes vote down vote up
public static String contextSetToString(LocaleManager localeManager, ContextSet set) {
    if (set.isEmpty()) {
        return Message.CONTEXT_PAIR_GLOBAL_INLINE.asString(localeManager);
    }

    StringBuilder sb = new StringBuilder();

    for (Context e : set) {
        sb.append(Message.CONTEXT_PAIR_INLINE.asString(localeManager, e.getKey(), e.getValue()));
        sb.append(Message.CONTEXT_PAIR_SEP.asString(localeManager));
    }

    return sb.delete(sb.length() - Message.CONTEXT_PAIR_SEP.asString(localeManager).length(), sb.length()).toString();
}
 
Example #28
Source File: ContextManager.java    From LuckPerms with MIT License 5 votes vote down vote up
public ImmutableContextSet getPotentialContexts() {
    ImmutableContextSet.Builder builder = new ImmutableContextSetImpl.BuilderImpl();
    for (ContextCalculator<? super S> calculator : this.calculators) {
        ContextSet potentialContexts;
        try {
            potentialContexts = calculator.estimatePotentialContexts();
        } catch (Throwable e) {
            this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst estimating potential contexts");
            e.printStackTrace();
            continue;
        }
        builder.addAll(potentialContexts);
    }
    return builder.build();
}
 
Example #29
Source File: MongoStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
private static List<Document> contextSetToDocs(ContextSet contextSet) {
    List<Document> contexts = new ArrayList<>(contextSet.size());
    for (Context e : contextSet) {
        contexts.add(new Document().append("key", e.getKey()).append("value", e.getValue()));
    }
    return contexts;
}
 
Example #30
Source File: ContextSetJsonSerializer.java    From LuckPerms with MIT License 5 votes vote down vote up
public static ContextSet deserializeContextSet(Gson gson, String json) {
    Objects.requireNonNull(json, "json");
    if (json.equals("{}")) {
        return ImmutableContextSetImpl.EMPTY;
    }

    JsonObject context = gson.fromJson(json, JsonObject.class);
    if (context == null) {
        return ImmutableContextSetImpl.EMPTY;
    }

    return deserializeContextSet(context);
}